Node.js Error: connect ECONNREFUSED [Solved]

avatar
Borislav Hadzhiev

Last updated: Apr 5, 2024
4 min

banner

# Node.js Error: connect ECONNREFUSED [Solved]

The Node.js Error: connect ECONNREFUSED occurs when a connection to the server could not be established.

To solve the error, make sure your application or database server is started and doesn't throw any errors before it's able to respond to HTTP requests.

node-js-error-connect-econnrefused

shell
UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED http://localhost:8000 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1144:16) (Use `node --trace-warnings ...` to show where the warning was created) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

The first thing you should try is to add the following 3 lines of code at the top of the entry file of your Node.js server (e.g. index.js).

index.js
process.on('uncaughtException', function (err) { console.log(err); });

The code simply handles uncaught exceptions and logs them to the terminal.

This would prevent your server from crashing before it's able to respond.

It is also useful for debugging because it logs uncaught exceptions to the terminal.

Here is an example of a simple Express, Node.js server.

index.js
const express = require('express'); const app = express(); // ๐Ÿ‘‡๏ธ Handle uncaught exceptions process.on('uncaughtException', function (err) { console.log(err); }); app.get('/', (req, res) => { res.json('Hello World!'); }); const port = 3445; app.listen(port, () => { console.log(`Example app listening on port ${port}`); }); throw new Error('An error occurred');

I can start the server with the node index.js command.

shell
node index.js

Now I can make HTTP requests to http://localhost:3445.

Even though the server throws an error right when it starts, the process.on() event handle handles the error, so the server doesn't crash instantly.

# Make sure you're sending requests to the correct URL and PORT

The error most often occurs for the following reasons:

  1. Specifying an incorrect URL or PORT when making HTTP requests.
  2. Forgetting to start your application server or database server before making HTTP requests.
  3. Forgetting to specify the protocol (http:// or https://) in the URL.
Make sure you have specified the correct URL and PORT when making requests.

If you specify an incorrect URL or PORT, you won't be able to establish a connection and the connect ECONNREFUSED is raised.

Here is an example HTTP request using fetch.

index.js
async function getData() { try { const response = await fetch('http://localhost:3445'); if (!response.ok) { throw new Error(`Error! status: ${response.status}`); } const result = await response.json(); console.log(result) return result; } catch (err) { console.log(err); } } getData()

The getData function makes an HTTP request to http://localhost:3455 (port 3455).

Make sure to specify the protocol (http or https) and ensure the endpoint and the PORT are correct.

The error is often raised due to connectivity issues caused by specifying an incorrect URL or PORT.

# Make sure to start your application or your database server first

Another common cause of the error is forgetting to start your application or database server.

You can start your application server in a separate terminal window before making HTTP requests.

Make sure that your database is running if you're trying to connect to a database.

For example, if you use MongoDB, start your Mongo server first and then your Node.js server.

If you're trying to connect to a database, check your database connection configuration. The database connection URL should point to the correct endpoint and port.

If you are testing on localhost, try to replace http://localhost:3000 with http://127.0.0.1:3000 (adjusting your port).

Here is an example.

index.js
async function getData() { try { // ๐Ÿ‘‡๏ธ Replaced http://localhost with http://127.0.0.1 const response = await fetch('http://127.0.0.1:3445'); if (!response.ok) { throw new Error(`Error! status: ${response.status}`); } const result = await response.json(); console.log(result) return result; } catch (err) { console.log(err); } } getData()

# Make sure the port you have started your server on is not taken

Make sure the port you have started your server on is not taken by a different application.

This would cause connectivity issues and the Node.js connect ECONNREFUSED error.

Make sure that a firewall is not preventing you from reaching the server.

# Make sure your NPM packages are installed

Open your terminal in your project's root directory (where your package.json) file is located and then run the npm install command.

shell
npm install

If the error is not resolved, try to delete your node_modules and package-lock.json (not package.json) files, re-run npm install and restart your IDE.

shell
# ๐Ÿ‘‡๏ธ (macOS/Linux) delete node_modules and package-lock.json rm -rf node_modules rm -f package-lock.json # ๐Ÿ‘‡๏ธ (Windows) delete node_modules and package-lock.json rd /s /q "node_modules" del package-lock.json # ๐Ÿ‘‡๏ธ clean your npm cache npm cache clean --force # ๐Ÿ‘‡๏ธ install packages npm install

# Try to restart your Development server

If the error persists, try to restart your IDE and development server.

Visual Studio Code often glitches and needs a reboot.

# Conclusion

To solve the error "Node.js Error: connect ECONNREFUSED", make sure:

  1. To specify the correct URL and PORT when making HTTP requests.
  2. Your application or database server is started and running.
  3. You haven't forgotten to specify the protocol (http:// or https://) in the URL.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev