如何在 node.js 中打印 http 服务器的地址?

How do you print the address of an http server in node.js?

这是我的代码:

var http = require('http');

function onRequest(req, res) {
    // do something
}

var server = http.createServer(onRequest);
server.listen(8000);
console.log("The server is now running on " + <<server.address>>);

我希望 <> 类似于“http://localhost:8000”。我该怎么做?

这应该会在服务器启动时为您提供主机名和端口:

var server  = require('http').createServer(onRequest);
var port = '8000';
server.listen(port, function(err) {
    console.log(err, require('os').hostname()+':'+port);
});
var http = require('http');
var server = http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(8080);
console.log('Server listening:', `http://${server.address().address}:${server.address().port}`);

我觉得你可以用

server.address()#

Added in: v0.1.90 Returns the bound address, the address family name, and port of the server as reported by the operating system. Useful to find which port was assigned when getting an OS-assigned address. Returns an object with port, family, and address properties: { port: 12346, family: 'IPv4', address: '127.0.0.1' }