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/');
官网的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);