When attempting to launch a Node.js/Express application, an ERR_CONNECTION_REFUSED message was received on localhost:3000

I've been troubleshooting an issue with my simple express app and I can't seem to figure out why it's not loading in any web browser or in Postman. Even though port 3000 doesn't appear to be in use, changing ports still results in the same error. The console logs show no errors except for ERR_CONNECTION_REFUSED across all apps. Below is a snippet of my JavaScript code, with a separate .env file specifying 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 already tried npm install, npm init, and nodemon which starts the server successfully with "App running on port 3000" message displayed in the terminal. However, trying to access the app in different browsers leads to the same outcome. I have disabled my firewall, cleared DNS cache, and browser cache in multiple browsers but the issue remains unresolved. Please advise on any further steps needed! Your help is highly appreciated.

Answer №1

  • check the environment variable process.env.PORT
const PORT = process.env.PORT || 3001
3000: accurate, since process.env.PORT is configured
3001: incorrect, as process.env.PORT is not configured
  • display the value of PORT in the app.listen
console.log("app running on port 3000");    // inaccurate
console.log(`app running on port ${PORT}`); // correct
  • invoke app.listen only once, and not twice with distinct ports
app.listen(process.emitWarning.PORT); // incorrect
app.listen(PORT, () => {});           // correct

Your concise code snippet 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 may include additional details later.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Storing data in a TypeBuffer and then retrieving it from a file can lead to surprising outcomes

Upon executing the following code: var list = new Uint32Array(16); for (var i=0; i<16; ++i) list[i] = i; fs.writeFileSync("list", new Uint8Array(list).buffer); console.log([].slice.call(new Uint32Array(fs.readFileSync("list")))); We anticipate the out ...

Display time series data from PHP by utilizing Flot Charts in jQuery

After receiving data from a database, which is formatted using PHP and returned as a JSON response for an Ajax call, I encountered an issue. Everything works fine and the data is plotted except when the X-Axis contains dates, in which case nothing gets plo ...

The Angular JavaScript page successfully compiles, yet displays only a blank screen

I am facing an issue with my Angular app where it compiles successfully, but the HTML page appears blank and my application is not displaying properly. I have encountered similar problems in the past which were often related to Imports, but this time I&apo ...

Creating a framework for sharing data between directives using Angular services

In my project, I have developed two directives named "mainPane" and "sidePane" displaying lists of items. These lists often contain overlapping content, allowing users to interact with the items in either list. My main requirement is that any changes mad ...

Encapsulate ng-style within quotation marks

I am trying to hide a span if the value of filters[*index*] is empty. var span = "<span ng-style='{ 'display': filters[" + filterIndex + "] == '' ? 'none' : 'inline-block' }'></span>" cell.html ...

What could be causing my function to output unicode replacement characters instead?

As I work on enhancing password security by implementing encryption, my goal is to store the hashes and perform encryption/decryption during signup/login processes. The encryption process works smoothly, converting from utf8 to hex without any issues. Howe ...

Utilize npm node to dynamically adjust screen resolution

Currently developing a game using electron. I'm experiencing FPS drops when running it in full-screen mode. To improve the game's performance, I need to change the screen resolution programmatically. My current resolution is 1280x800, but I would ...

Understanding Three.js Fundamentals: Resolving GLTFLoader Animation and Variable Not Found Issues

My understanding of JS is very basic. After exploring the three.js docs on Loading 3D models, I managed to successfully render a 3D object and center it: const loader = new GLTFLoader(); loader.load( 'Duck.gltf', function ( duck ) { con ...

Guide to waiting for API responses with redux-saga

I have a React-Typescript app with backend calls using React Saga. I'm facing an issue where when one of my frontend functions makes a backend call, the next function starts executing before the previous one finishes. Currently, I'm using the SE ...

Material Design - The element provided is not valid: it should be a string for built-in components or a class/function for composite components, but instead it is an object

How are you today? I am currently working on a React project using Webpack and Babel. I encountered an issue when trying to incorporate Material UI components from https://mui.com/. Whenever I import a MUI component into my project, I receive the followin ...

A Guide to Displaying HTTP Error Messages on the Angular Login Page

When encountering a form validation failure on my login page, I utilize ngMessage to display an error message. However, I now want this div to be displayed in the event of an HTTP 500 error. While I can retrieve the corresponding error message when an HTTP ...

Pressing the "Contact Us" button is not causing the modal to open

The "Contact Us" button on my Bootstrap 5.2 modal is not opening the Modal. What could I be missing? <!DOCTYPE html> <html lang="html" xmlns="http://www.w3.org/1999/html"> <head> <meta charset="utf-8"&g ...

I am interested in incorporating pinia state management into my Vue 3 project

I'm currently working on implementing pinia state management in Vue 3, but I've encountered the following error: Module not found: Error: Can't resolve 'src/stores/cart' in 'C:\Users\Ali Haider\theme-project&b ...

I am having trouble getting my Jquery to locate the panelid

I tried following a tutorial to improve my coding skills, but I'm facing issues with my code. It seems like my jQuery isn't able to locate the panelid. I can successfully alert the panelids, but the functionality of clicking on "läs mer" and dis ...

How to eliminate grid lines and labels from Chart.js graphs?

Is there a way to hide the grid lines in the Radar chart using chart.js v2 for react? Desired Result, I am looking to hide the inner lines and numbers while keeping the outermost line visible. I tried to implement the following code, but it resulted in a ...

Can content be dynamically loaded through ajax in Simile Timeline instead of being loaded upfront?

I am currently utilizing the JavaScript Simile Timeline which includes timeline items with extensive description fields. Rather than including all this information in the initial JSON payload data, I only want to load it when a user clicks on a timeline it ...

What could be causing this code to continuously loop without end?

I've been scratching my head trying to understand why this code isn't working. var refP = []; var calculateDistance = function (p1, p2) { return dist(p1.x, p1.y, p2.x, p2.y); } while (refP.length < 24) { var point = { x: -1, ...

Looping through multi-dimensional JSON objects with jQuery

Hello there, I'm currently facing some challenges in getting the screen below to work properly: Project progress screen I have generated the following JSON data from PHP and MYSQL. My goal is to display the project alongside user images and names whe ...

The problem encountered with Angular ngrx: TypeError when attempting to freeze array buffer views containing elements

I'm running into a problem with ngrx. I have an array in my state to which I am trying to add objects. Everything seems to be working fine as I can see the values in my store when I console log them. However, the redux dev tools and console are throwi ...

Migrating nl2br to JavaScript/React - Techniques for manually encoding text?

Currently in the process of transitioning a small project from Flask + server-side template rendering to Flask + React. One particular component utilizes a Jinja2 custom filter called nl2br, which essentially converts newlines in plain text into <p> ...