如何让Node.JS Express只收听本地主机? [英] How to get Node.JS Express to listen only on localhost?
问题描述
我预计这将工作:
app.listen(3001,'localhost');
或
app.listen(3001,'127.0.0.1');
...但是我收到一个错误:
node.js: 201
throw e; // process.nextTick错误,或第一次勾选时出现'error'事件
^
TypeError:无法在Object处读取空值
的属性'port'。< anonymous> (/home/ctoledo/hive-go/go.js:204:76)
在Module._compile(module.js:441:26)
在Object..js(module.js:459 :$)
在Module.load(module.js:348:31)
在Function._load(module.js:308:12)
在Array.0(module.js: 479:10)
在EventEmitter._tickCallback(node.js:192:40)
运行应用程序而不指定主机名可以正常工作,即, app.listen(3001);
。
我正在运行Node v0.6.14 ,并表达@ 2.5.5 ,并阅读了 google小组讨论,并发现此评论说:此方法与节点的相同的参数http.Server#listen()
。
感谢任何帮助
感谢您的信息,认为我看到问题。这是在 hive-go
中的错误,只有在添加主机时才会显示。最后一行是:
app.listen(3001);
console.log(...%s模式下的端口%,app.address()。port,app.settings.env);
当您在第一行添加主机时,调用 app.address()。port
。
问题是 .listen()
。真的应该是这样做 console.log
调用里面的一个回调传递给listen。添加主机时,它会尝试进行DNS查找,这是异步的。所以当该行尝试获取地址时,由于DNS请求正在运行,因此还没有一个,所以它崩溃。
尝试这样:
app.listen(3001,'localhost',function(){
console.log(... port%d in% s模式,app.address()。port,app.settings.env);
});
I have an application that I have behind a reverse proxy, I would like for it to only listen to localhost/127.0.0.1.
I expected this to work:
app.listen(3001, 'localhost');
or
app.listen(3001, '127.0.0.1');
...but instead I get an error:
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Cannot read property 'port' of null
at Object.<anonymous> (/home/ctoledo/hive-go/go.js:204:76)
at Module._compile (module.js:441:26)
at Object..js (module.js:459:10)
at Module.load (module.js:348:31)
at Function._load (module.js:308:12)
at Array.0 (module.js:479:10)
at EventEmitter._tickCallback (node.js:192:40)
Running the application without a specifying the hostname works fine, ie., app.listen(3001);
.
I am running Node v0.6.14 and express@2.5.5 and have read this google groups discussion and have found this comment in Express application.js saying: "This method takes the same arguments as node's http.Server#listen()
."
Thanks for any help.
Thanks for the info, think I see the problem. This is a bug in hive-go
that only shows up when you add a host. The last lines of it are:
app.listen(3001);
console.log("... port %d in %s mode", app.address().port, app.settings.env);
When you add the host on the first line, it is crashing when it calls app.address().port
.
The problem is the potentially asynchronous nature of .listen()
. Really it should be doing that console.log
call inside a callback passed to listen. When you add the host, it tries to do a DNS lookup, which is async. So when that line tries to fetch the address, there isn't one yet because the DNS request is running, so it crashes.
Try this:
app.listen(3001, 'localhost', function() {
console.log("... port %d in %s mode", app.address().port, app.settings.env);
});
这篇关于如何让Node.JS Express只收听本地主机?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!