简体   繁体   中英

Server address and port in nodejs and express using http.createServer

new to node and express. Need to know how to fetch the servers IP and Port. Tried a few things:

const express = require('express'); 
const app = express(); 
var http = require('http'); 
app.set('port',12346); 
var httpServer = http.createServer(app).listen(app.get('port'));  
function getMethod(req,res) {
    console.log("Server Port is: "+ app.get('port'));
    // console.log("Server Port is: "+ httpServer.address);
    console.log("Connection Type: "+ req.protocol);
    res.send("Hello world!"); 
} 
app.get('/', getMethod);

In the code above app.get returns me the servers port but if I query httpServer.address it returns undefined and app.address().port returns an error.
Is there a way to get it without setting it in the app?

http.Server 's listen is asynchronous, and you should not call address() until the listening event has been dispatched (from the docs Don't call server.address() until the 'listening' event has been emitted. ).

You can do this a few ways, subscribing to the listening callback:

httpServer.on('listening', function () {
  console.log(app.address().port)
})

Or simply using app.listen (which creates an http.Server ) and checking the instance's port in the callback that listen accepts:

let appInstance = app.listen(1337, function () {
  console.log(`'Server listening at: ${appInstance.address().port}`)
})

This removes the need to require the http module and simplifies the code somewhat.

The set / get methods on app allow you to set and retrieve arbitrary values on an express application. Some of those values are "special" (see the docs ) and affect the behavior of the application, but there's nothing stopping you from setting a property like port ; the issue there is that it won't actually change the port that the application listens on.

Try :

console.log('Port :' + httpServer.address().port);
console.log('Server:' + httpServer.address().address);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM