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

标签 node.js web-services http ip-address

这是我的代码:

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 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' }

关于node.js - 你如何在 node.js 中打印 http 服务器的地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41540093/

相关文章:

javascript - Knex.js 从选择中插入

node.js - 是什么导致 web3js 测试代码中出现 MaxListenersExceededWarning 警告

android - 无法使用 Volley 将 JSONArray 转换为 JSONObject

c# - 使用 LINQ 在 WebService 中自动完成

javascript - 通过 http 发送非常大的播放列表数据的最有效方法是什么?

security - 常用的 PKCS 标准 : PKCS#7, PKCS#10 和 PKCS#12 有什么用?

node.js - Vue.js 2 身份验证 JWT

javascript - 服务器崩溃,重启时发送消息(Node.js/Socket.io)

c# - 您如何设置解决方案配置特定的配置文件?

spring - http 响应中缺少 Angular2 JWT 授权 header (添加了 CORS 支持)