Heroku + node.js error (Web process failed to bind to $PORT within 60 seconds of launch)

前端 未结 24 1908
梦如初夏
梦如初夏 2020-11-22 05:42

I have my first node.js app (runs fine locally) - but I am unable to deploy it via heroku (first time w/ heroku as well). The code is below. SO doesn\'t let me write so much

24条回答
  •  北海茫月
    2020-11-22 06:24

    From the heroku bash process, pass down the value of $PORT to your node app using an options parser like yargs.

    Here is an example of how you might do that. On the scripts object, inside package.json, add a start method "node server --port $PORT".

    In your server file, use yargs to get the value from the port option (--port $PORT) of the start method:

    const argv = require('yargs').argv;
    const app = require('express')();
    
    const port = argv.port || 8081;
    
    app.listen(argv.port, ()=>{
        console.log('Probably listening to heroku $PORT now ', argv.port); // unless $PORT is undefined, in which case you're listening to 8081.
    });
    

    Now when your app starts, it will bind to the dynamically set value of $PORT.

提交回复
热议问题