NodeJS: How to get the server's port?

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

提交回复
热议问题