Nodejs 服务器主机名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12562065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:20:51  来源:igfitidea点击:

Nodejs Server Hostname

httpnode.jsexpress

提问by Craig Myles

Ok, so it seems pretty easy in Node.js to get the hostname of the request being made to my server:

好的,所以在 Node.js 中获取向我的服务器发出的请求的主机名似乎很容易:

app.get('/', function(req,res){
    console.log(req.headers.host);
});

Is there an easy way to determine the hostname of my actual http server? For example, my server is running at the address http://localhost:3000- can I programatically determine this address? I am using expressjs.

有没有一种简单的方法来确定我的实际 http 服务器的主机名?例如,我的服务器正在该地址运行http://localhost:3000- 我可以通过编程方式确定该地址吗?我正在使用 expressjs。

回答by Jason Brumwell

Yes you can using the;

是的,您可以使用;

var express = require('express'),
    app = express(),
    server  = require('http').createServer(app);

server.listen(3000, function(err) {
        console.log(err, server.address());
});

should print

应该打印

{ address: '0.0.0.0', family: 'IPv4', port: 3000 }

you can also retreive the hostname for the os by the following;

您还可以通过以下方式检索操作系统的主机名;

require('os').hostname();