I'm using Express.js/Postgres as my server and I have it set to run on port 3030:
app.set('port', process.env.PORT || 3030); And I'm listening to it:
app.listen(() => { console.log( `The server is running on port '${app.get('port')}'` ) }) In the console I see this:
[nodemon] 1.12.1 [nodemon] to restart at any time, enter `rs` [nodemon] watching: *.* [nodemon] starting `node server/server.js` The server is running on port '3030' The problem is found when I go to localhost:3030 in my browser. Instead of the page I want, I get this:
This site can’t be reached localhost refused to connect. Search Google for localhost 3030 ERR_CONNECTION_REFUSED I've shut down any and all terminals (nothing could potentially be running from another window), I've tried deleting the entire directory before cloning back down from Github. I've even uninstalled Postgres via Brew. I've run into this problem before, at which point I killed programs that were using specific ports via their PID and that mysteriously helped, but it's not working this time.
Here's the link for my Github repo
Any help?
2 Answers
The problem is app.set('port'). This doesn't set the port applicable to app.listen(). Rather, it sets the variable port that can be accessed with app.get('port').
I would recommend setting a variable, such as PORT to process.env.PORT || 3030. As it currently stands I believe express is choosing a random port to use.
There's some more info in this answer: javascript - app.set('port', 8080) versus app.listen(8080) in Express.js
This may not have been the only thing wrong (everything is working now, anyways), but there was a problem in the app.listen() method. The first argument was not meant to be a callback as I was giving it, but a path that references what exactly it's listening to. The callback is optional, but only as a second argument. Here's the link to the Express docs.
Using app.set('port', process.env.PORT || 3030) sets the port to either process.env.PORT, or if that isn't true, than it defaults to port 3030. In a production or testing environment process.env.PORT will have a value and ignore 3030 altogether.