我正在尝试在运行 ubuntu 14.04 和 apache 2.4.7 的 aws 服务器上运行基本的 node.js 文件
var http = require('http');
var hostname = '33.33.33.33';
var port = 3000;
var server = http.createServer(function(req, res) {
console.log(req.headers);
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>Hello World</h1>');
});
server.listen(port, hostname, function() {
console.log('Server running at http://${hostname}:${port}/');
});
主机名只是服务器的 IP。应该是别的什么吗?主机名应该是 IP 还是其他名称?
上面的代码给出了以下错误:
events.js:72
throw er; // Unhandled 'error' event
^
Error: listen EADDRNOTAVAIL
at errnoException (net.js:901:11)
at Server._listen2 (net.js:1020:19)
at listen (net.js:1061:10)
at net.js:1135:9
at dns.js:72:18
at process._tickCallback (node.js:415:13)
at Function.Module.runMain (module.js:499:11)
at startup (node.js:119:16)
at node.js:901:3
********更新************
我已经使用本地主机更新了我的代码。这消除了错误并允许我运行 .js 文件。但是我无法从服务器访问该文件。我像这样输入 IP
**.**.**.**:3000
这将返回消息:
This site can’t be reached
**.**.**.** refused to connect.
ERR_CONNECTION_REFUSED
我还尝试访问该文件在服务器上所在的位置,但得到了相同的结果。
**.**.**.**:3000/nodelearning/c1_node_week1/node-express
运行后:
node myNodeApp.js
在终端中,我只需要从网络浏览器访问服务器的IP,对吗?我是否只需要访问根 **.**.**.**:3000
还是需要访问 Node 文件 **.** 的特定位置。 **.**:3000/learningNode/myNodeApp.js
我只需要访问root权限就可以了吗?
那么 **.**.**.**:3000
应该可以工作吗?
下面是我能够运行的 .js 文件。但我无法访问。
var express = require('express'),
http = require('http');
var hostname = 'localhost';
var port = 3000;
var app = express();
app.use(function (req,res, next) {
console.log(req.headers);
res.writeHead(200, {'Content-Type': 'text/html' });
res.end('<html><body><h1>Hello World</h1></body></html>');
});
var server = http.createServer(app);
server.listen(port, hostname, function(){
console.log('Server running at http:// NVM');
});
干杯
最佳答案
问题在于
var hostname = '33.33.33.33';
因为当路由被回收时,新的IP地址被分配给机器。所以这会失败。作为建议,在 listen()
中跳过主机参数,或者如果您仍然想使用主机名,请使用
var hostname = '127.0.0.1';
或
var hostname = 'localhost';
希望有帮助:)
关于在 aws ubuntu 服务器上运行 server.listen 时出现 node.js 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36110095/