快递应用服务器。监听所有接口而不是仅监听本地主机
express app server . listen all interfaces instead of localhost only
我对这些东西很陌生,正在尝试制作一些快速应用程序
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')
});
当我使用以下命令启动服务器时:
node server.js
一切顺利。
我在控制台上看到了
listen:3000
当我尝试时
curl http://localhost:3000
我明白了'ok'。
当我尝试时
telnet localhost
明白了
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'
但是当我尝试
netstat -na | grep :3000
明白了
tcp 0 0 0.0.0.0:3000 0.0.0.0:* LISTEN
问题是:为什么它监听所有接口而不是只监听本地主机?
OS 是 linux 没有任何哨子的薄荷 17。
如果您在调用 app.listen 时不指定主机,服务器将在所有可用接口上 运行,即 0.0.0.0
您可以使用以下代码绑定IP地址
app.listen(3000, '127.0.0.1');
如果你想运行服务器在所有界面使用下面的代码
app.listen(3000, '0.0.0.0');
或
app.listen(3000)
From the documentation: 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().
var express = require('express');
var app = express();
app.listen(3000, '0.0.0.0');
文件:app.listen([port[, host[, backlog]]][, callback])
示例:
const express = require('express');
const app = express();
app.listen('9000','0.0.0.0',()=>{
console.log("server is listening on 9000 port");
})
注意:0.0.0.0 被指定为主机以便从外部接口访问
我对这些东西很陌生,正在尝试制作一些快速应用程序
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')
});
当我使用以下命令启动服务器时:
node server.js
一切顺利。
我在控制台上看到了
listen:3000
当我尝试时
curl http://localhost:3000
我明白了'ok'。
当我尝试时
telnet localhost
明白了
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'
但是当我尝试
netstat -na | grep :3000
明白了
tcp 0 0 0.0.0.0:3000 0.0.0.0:* LISTEN
问题是:为什么它监听所有接口而不是只监听本地主机?
OS 是 linux 没有任何哨子的薄荷 17。
如果您在调用 app.listen 时不指定主机,服务器将在所有可用接口上 运行,即 0.0.0.0
您可以使用以下代码绑定IP地址
app.listen(3000, '127.0.0.1');
如果你想运行服务器在所有界面使用下面的代码
app.listen(3000, '0.0.0.0');
或
app.listen(3000)
From the documentation: 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().
var express = require('express');
var app = express();
app.listen(3000, '0.0.0.0');
文件:app.listen([port[, host[, backlog]]][, callback])
示例:
const express = require('express');
const app = express();
app.listen('9000','0.0.0.0',()=>{
console.log("server is listening on 9000 port");
})
注意:0.0.0.0 被指定为主机以便从外部接口访问