Nodejs Server Hostname

2019-03-25 07:00发布

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);
});

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.

2条回答
beautiful°
2楼-- · 2019-03-25 07:27

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();
查看更多
混吃等死
3楼-- · 2019-03-25 07:44

0.0.0.0 indicates that it is listening on all of the network interfaces (IP addresses) available on the host.

查看更多
登录 后发表回答