NodeJS: How to get the server's port?

后端 未结 19 1394
醉梦人生
醉梦人生 2020-12-02 05:47

You often see example hello world code for Node that creates an Http Server, starts listening on a port, then followed by something along the lines of:

conso         


        
相关标签:
19条回答
  • 2020-12-02 06:29

    In case when you need a port at the time of request handling and app is not available, you can use this:

    request.socket.localPort
    
    0 讨论(0)
  • 2020-12-02 06:30
    var express = require('express');    
    var app = express();
        app.set('port', Config.port || 8881);
        var server = app.listen(app.get('port'), function() {
            console.log('Express server listening on port ' + server.address().port); 
        });
    

    Express server listening on port 8881

    0 讨论(0)
  • 2020-12-02 06:31

    If you're using express, you can get it from the request object:

    req.app.settings.port // => 8080 or whatever your app is listening at.
    
    0 讨论(0)
  • 2020-12-02 06:33

    The easier way is just to call app.get('url'), which gives you the protocol, sub domain, domain, and port.

    0 讨论(0)
  • 2020-12-02 06:34

    The findandbind npm addresses this for express/restify/connect: https://github.com/gyllstromk/node-find-and-bind

    0 讨论(0)
  • 2020-12-02 06:35

    You might be looking for process.env.PORT. This allows you to dynamically set the listening port using what are called "environment variables". The Node.js code would look like this:

    const port = process.env.PORT || 3000; 
    app.listen(port, () => {console.log(`Listening on port ${port}...`)}); 
    

    You can even manually set the dynamic variable in the terminal using export PORT=5000, or whatever port you want.

    0 讨论(0)
提交回复
热议问题