【发布时间】:2021-05-09 09:37:53
【问题描述】:
我正在学习如何在服务器(不是我的本地机器)中使用 Node.js 应用程序。在这种情况下,我关注 this tutorial 是为了创建一个简单的 Web 服务器。
我已经安装了 Node.js,并通过 CLI 测试了 它可以工作。我可以运行 javascript 代码、在 CLI 中生成输出等。但我无法使用浏览器通过 URL 使应用程序工作。
我的app文件夹结构很简单:
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 转到应用程序的文件夹并运行应用程序 (node index.js),我可以看到预期的 console.log() 输出(5000 端口的 Node.js Web 服务器正在运行..)。但是,如果我转到指向该文件夹的 URL,我希望输出 <html><body><p>This is home Page.</p></body></html>,它就不起作用(请参阅下面的内容)。
我有一个域 (http://example.com),在应用程序的文件夹中有文档根目录。这是我尝试过的:
- https://example.com //浏览器显示index.js的源码
- https://example.com:5000 //浏览器显示 ERR_CONNECTION_TIMED_OUT
- https://example.com/:5000 //浏览器显示404错误
- https://example.com/index.js //浏览器显示index.js的源码
- https://example.com/index.js:5000 //浏览器显示404错误
这些都没有给出我期望的响应。我不知道这是否是我的文件结构、服务器配置的问题......但我一直在环顾四周,我不明白为什么这个基本示例在我的情况下不起作用,显然我是遗漏了什么。任何帮助将不胜感激!
编辑: 我试图运行这个应用程序的服务器是一台装有 CentOS 7 的 LAMP 机器。
【问题讨论】:
-
“Jt 不起作用”。任何事物? ????。
-
"我有一个域 (example.com),其文档根位于应用程序的文件夹中。" - 域并不重要,只是它指向您的网络服务器。但是您需要告诉我们更多关于您的服务器安装的信息。您在说什么“文档根目录”?这是一个预先配置了软件以提供静态文件的服务器吗?这不是你运行 node.js 应用程序的方式。
-
它对我有用。如果您正在获取
index.js文件的源代码,那么您正在端口 80 上运行另一个 Web 服务器,但如果您正在获取console.log行,那么在端口5000上它应该可以工作。 -
这也没有使用
https,所以你应该使用http,正确的url是example.com:5000/而不是example.com/:5000 -
您使用的是哪个 Linux? ????。
标签: javascript node.js lamp