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 http://127.0.0.1:1337/');
习惯性写web service时,都是监听的hostname为127.0.0.1,那么我要监听localhost和本地IP呢?一下子糊涂了。
listen(1337, '127.0.0.1')
listen(1337, '192.168.1.110')
listen(1337, 'localhost')
这样吗?但是这样子本地的IP访问是无效的,怎么办?发现自己犯了个愚蠢的错误,官网的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);