我正在学习如何在服务器(而不是本地计算机)中使用Node.js应用程序。在这种情况下,我将按照本教程来创建一个简单的Web服务器。
我已经安装了Node.js,并通过CLI对其进行了测试。我可以运行javascript代码,在CLI中生成输出,等等。但是我无法使用浏览器通过URL使应用程序正常工作。
我拥有的应用程序文件夹结构非常简单:
index.js
package.json
package-lock.json
这是我目前正在使用的代码index.js
:
var http = require('http'); // 1 - Import Node.js core module
var server = http.createServer(function (req, res) { // 2 - creating server
if (req.url == '/') { //check the URL of the current request
// set response header
res.writeHead(200, { 'Content-Type': 'text/html' });
// set response content
res.write('<html><body><p>This is home Page.</p></body></html>');
res.end();
}
else if (req.url == "/student") {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<html><body><p>This is student Page.</p></body></html>');
res.end();
}
else if (req.url == "/admin") {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<html><body><p>This is admin Page.</p></body></html>');
res.end();
}
else
res.end('Invalid Request!');
});
server.listen(5000); //3 - listen for any incoming requests
console.log('Node.js web server at port 5000 is running..')
如果我通过CLI转到应用程序的文件夹并运行应用程序(节点index.js),则可以看到预期的console.log()输出(端口5000上的Node.js Web服务器正在运行。)。但是,如果我转到指向该文件夹的URL(我希望将其输出)<html><body><p>This is home Page.</p></body></html>
,则该URL将无法正常工作(请参阅下面的内容)。
我在应用程序的文件夹中有一个域(http://example.com),其文档根目录为。这是我尝试过的:
这些都不给我期望的答复。我不知道这是否是我的文件结构,服务器配置方面的问题...但是我一直在寻找,并且我不知道为什么这个基本示例在我的情况下不起作用,显然遗漏了什么。任何帮助将非常感激!
编辑:我试图运行该应用程序的服务器是带有CentOS 7的LAMP机器。
我已经签入服务器(Nginx),您的代码运行正常。
阅读@MinusFour的评论后,我怀疑您没有在服务器的安全组中打开5000端口。
安全组就像
如果那不起作用,您还可以检查服务器的防火墙设置。
至于您的域表达式:
您可以参考https://support.google.com/gsa/answer/6329145?hl=zh_CN
我没有50多个信誉的评论,所以我必须在这里回答。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句