Node.js/Express.js App Only Works on Port 3000

后端 未结 16 2186
暖寄归人
暖寄归人 2020-12-12 13:23

I have a Node.js/Express.js app running on my server that only works on port 3000 and I\'m trying to figure out why. Here\'s what I\'ve found:

  • Without specifyi
相关标签:
16条回答
  • 2020-12-12 14:00

    Noticed this was never resolved... You likely have a firewall in front of your machine blocking those ports, or iptables is set up to prevent the use of those ports.

    Try running nmap -F localhost when you run your app (install nmap if you don't have it). If it appears that you're running the app on the correct port and you can't access it via a remote browser then there is some middleware or a physical firewall that's blocking the port.

    Hope this helps!

    0 讨论(0)
  • 2020-12-12 14:03

    Try this

    $ PORT=8080 node app.js
    
    0 讨论(0)
  • 2020-12-12 14:03

    I am using the minimist package and the node startup arguments to control the port.

    node server.js --port 4000

    or

    node server.js -p 4000

    Inside server.js, the port can be determined by

    var argv = parseArgs(process.argv.slice(2))
    
    const port = argv.port || argv.p || 3000;
    console.log(`Listening on port ${port}...`)
    
    //....listen(port);
    

    and it defaults to 3000 if no port is passed as an argument.

    You can then use listen on the port variable.

    0 讨论(0)
  • 2020-12-12 14:04

    I think the best way is to use dotenv package and set the port on the .env config file without to modify the file www inside the folder bin.

    Just install the package with the command:

    npm install dotenv
    

    require it on your application:

    require('dotenv').config()
    

    Create a .env file in the root directory of your project, and add the port in it (for example) to listen on port 5000

    PORT=5000
    

    and that's it.

    More info here

    0 讨论(0)
  • 2020-12-12 14:05

    Answer according to current version of express

    If you talk about the current version of express, if you run app.listen() to start listening without specifying port, Express will chose a random port for your application, to find out about which port it is currently running on use

    app.listen(0, () => {
        console.log(app.address().port)
    }
    

    should output the port of your app. Moreover that first parameter 0 can be totally ignored but is not recommended

    0 讨论(0)
  • 2020-12-12 14:07

    The default way to change the listening port on The Express framework is to modify the file named www in the bin folder.

    There, you will find a line such as the following

    var port = normalizePort(process.env.PORT || '3000');
    

    Change the value 3000 to any port you wish.

    This is valid for Express version 4.13.1

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