您的位置:首页 > Web前端 > Node.js

nodejs中创建web服务被忽略的坑---listen hostname

2015-11-04 12:16 651 查看
nodejs中创建web服务时,习惯看官网例子

var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at 官网的API上说到:' target='_blank'>http://127.0.0.1:1337/');官网的API上说到:
server.listen(port, [hostname], [backlog], [callback])#

Begin accepting connections on the specified port and hostname. If the hostname is omitted, the server will accept connections directed to any IPv4 address (INADDR_ANY).
里面说到如果忽略了hostname,那么服务器将会接受所有IPV4地址的链接,IPv4地址包括127.0.0.1 localhost和本地IP。没有认真看API,以后要注意。那么这样做就可以实现监听本地IP、localhost、127.0.0.1了:

var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息