Search code examples
javascriptexpresslocalhost

localhost:3000 ERR_CONNECTION_REFUSED returned when trying to run a node/express app


I am trying to run a simple express app and I can't seem to figure out why I can't view my app in a web browser, or in postman. Looking into my system port 3000 does not appear to be in use, I have also tried several different ports and receive the same error. There is nothing in console logs, and this is the ERR_CONNECTION_REFUSED is the only error code present across all apps. Below is my JS code, there is a separate .env file with PORT = 3000.

require('dotenv').config()
const express = require("express");
const app = express();

app.use('/places', require('./controllers/places'))

app.get("/", (req, res) => {
  res.send("Hello World!");
});

app.get('*', (req, res) => {
    res.status(404).send('<h1>404 Page </h1>')
})

app.listen(process.emitWarning.PORT);
const PORT = process.env.PORT;

app.listen(PORT, () => {
  console.log("app running on port 3000");
});

I have run npm install, npm innit, and when I run nodemon the server starts fine with "app running on port 3000" logged into the terminal.Attempting to run the app in different browsers creates the same outcome. I have completely disabled my firewall, flushed my DNS, and cleared my browser cache across all browsers and the same issue persists. If anything else is needed please let me know! Thanks for any advice, it is greatly appreciated.


Solution

    • check environment variable process.env.PORT
    const PORT = process.env.PORT || 3001
    3000: correct, process.env.PORT is set
    3001: wrong,   process.env.PORT is not set
    
    • print the value of PORT in app.listen
    console.log("app running on port 3000");    // wrong
    console.log(`app running on port ${PORT}`); // correct
    
    • call app.listen once, not twice with different ports
    app.listen(process.emitWarning.PORT); // wrong
    app.listen(PORT, () => {});           // correct
    

    Your minimal code should be:

    require('dotenv').config()
    const express = require("express");
    
    const app = express();
    
    app.get("/", (req, res) => {
      res.send("Hello World!");
    });
    
    const PORT = process.env.PORT || 3000;
    
    app.listen(PORT, () => {
      console.log(`app running on port ${PORT}`);
    });
    

    You can add everything else afterwards.