Javascript 快递应用服务器。只听所有接口而不是本地主机

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33953447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:42:31  来源:igfitidea点击:

express app server . listen all interfaces instead of localhost only

javascriptnode.jsexpressmean

提问by Pavel L

I'm very new for this stuff, and trying to make some express app

我对这个东西很陌生,并试图制作一些快速的应用程序

var express = require('express');
var app = express();

app.listen(3000, function(err) {
    if(err){
       console.log(err);
       } else {
       console.log("listen:3000");
    }
});

//something useful
app.get('*', function(req, res) {
  res.status(200).send('ok')
});

When I start the server with the command:

当我使用以下命令启动服务器时:

node server.js 

everything goes fine.

一切顺利。

I see on the console

我在控制台看到

listen:3000

and when I try

当我尝试

curl http://localhost:3000

I see 'ok'.

我看到'好的'。

When I try

当我尝试

telnet localhost

I see

我懂了

Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]' 

but when I try

但是当我尝试

netstat -na | grep :3000

I see

我懂了

tcp  0  0 0.0.0.0:3000   0.0.0.0:*  LISTEN

The question is: why does it listen all interfaces instead of only localhost?

问题是:为什么它会侦听所有接口而不是仅侦听 localhost?

The OS is linux mint 17 without any whistles.

操作系统是 linux mint 17,没有任何口哨声。

回答by Vishnu

If you use don't specify host while calling app.listen, server will run on all interfaces available i.e on 0.0.0.0

如果您在调用时不指定主机app.listen,则服务器将在所有可用接口上运行,即0.0.0.0

You can bind the IP address using the following code

您可以使用以下代码绑定IP地址

app.listen(3000, '127.0.0.1');

回答by Julien Le Coupanec

From the documentation: app.listen(port, [hostname], [backlog], [callback])

从文档app.listen(port, [hostname], [backlog], [callback])

Binds and listens for connections on the specified host and port. This method is identical to Node's http.Server.listen().

绑定并侦听指定主机和端口上的连接。此方法与 Node 的 http.Server.listen() 相同。

var express = require('express');
var app = express();
app.listen(3000, '0.0.0.0');

回答by Thavaprakash Swaminathan

document: app.listen([port[, host[, backlog]]][, callback])

文档: app.listen([port[, host[, backlog]]][, callback])

example:

例子:

const express = require('express');
const app = express();
app.listen('9000','0.0.0.0',()=>{
      console.log("server is listening on 9000 port");
})

Note: 0.0.0.0 to be given as host in order to access from outside interface

注意:0.0.0.0 作为主机提供以便从外部接口访问