Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expressjs server address host returns nothing

Following the standard ExpressJs hello word example, i get a host of ' : : '.

Why does this happen?

hello word example:

var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
});

I found a tip that was add 'localhost' after port parameter. It solved when i was looking just my pc, but it wont work over the network. What should i do?

like image 544
Brenno Leal Avatar asked Sep 15 '15 16:09

Brenno Leal


2 Answers

I tried the example and had the same output for hostname '::', I did the following change as a workaround:

 var server = app.listen(3000, 'localhost', function () {
     var host = server.address().address;
     var port = server.address().port;
     console.log('Example app listening at http://%s:%s', host, port);
});

output:

Example app listening at http://127.0.0.1:3000

like image 119
lsampaio Avatar answered Oct 10 '22 16:10

lsampaio


This will give you the results you are looking for. You should not need to include 'localhost'

var server = app.listen(3000, function () {
    var port = server.address().port;
    require('dns').lookup(require('os').hostname(), function (err, add, fam) {
        debug('Example app listening at http://%s:%s', add, port);
    })
});
like image 33
Michael Hobbs Avatar answered Oct 10 '22 15:10

Michael Hobbs