Nodejs服务器主机名 [英] Nodejs Server Hostname

查看:142
本文介绍了Nodejs服务器主机名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,Node.js看起来很容易得到我的服务器请求的主机名:

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

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

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

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.

推荐答案

是的,你可以使用;

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

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

应该打印

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

您还可以通过以下方式检索os的主机名:

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

require('os').hostname();

这篇关于Nodejs服务器主机名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆