NodeJS: How to get the server's port?

后端 未结 19 1583
醉梦人生
醉梦人生 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:39

    const express = require('express');                                                                                                                           
    const morgan = require('morgan')
    const PORT = 3000;
    
    morgan.token('port', (req) => { 
        return req.app.locals.port; 
    });
    
    const app = express();
    app.locals.port = PORT;
    app.use(morgan(':method :url :port'))
    app.get('/app', function(req, res) {
        res.send("Hello world from server");
    });
    
    app1.listen(PORT);
    

提交回复
热议问题