DEV Community

Suhail Akhtar
Suhail Akhtar

Posted on • Originally published at suhail.hashnode.dev on

Nodejs Fix Error connect ECONNREFUSED ::1:80 while using localhost

Introduction

Node.js serves as a powerful platform for building server-side applications, but encountering errors, especially during local development, can disrupt progress. One such error is connect ECONNREFUSED ::1:80, commonly faced while attempting to connect to a local server.

Understanding the Error

The error message connect ECONNREFUSED ::1:80 signifies that the Node.js application is attempting to connect to the IPv6 loopback address (::1) on port 80, commonly used for HTTP traffic. However, the connection is being refused, leading to the error.

const axios = require("axios")try { const { data } = await axios.get('http://localhost')} catch (error) { console.log(error.message) // output: "connect ECONNREFUSED ::1:80"}
Enter fullscreen mode Exit fullscreen mode

Solution 1

You can fix the connect ECONNREFUSED ::1:80 error by explicitly specifying the IPv4 loopback address (127.0.0.1) instead of relying on the IPv6 (::1) address.

const axios = require("axios")try { const { data } = await axios.get('http://127.0.0.1') // Success Response} catch (error) { console.log(error.message)}
Enter fullscreen mode Exit fullscreen mode

Solution 2

Starting from Node.js 17 IPv6 connections are prioritized when making network calls. This is great for future-proofing your code, but it can cause problems if the server you're trying to reach only supports IPv4. This is where setDefaultResultOrder() comes in like a knight in shining armor.

const axios = require("axios")const { setDefaultResultOrder } = require("dns");setDefaultResultOrder("ipv4first");try { const { data } = await axios.get('http://localhost') // Success Response} catch (error) { console.log(error.message)}
Enter fullscreen mode Exit fullscreen mode

Solution 3

Degrading the version of Nodejs runtime to Nodejs 16 or lower can also fix the issue but it is not recommended.

Try Yourself

https://runkit.com/gitsambhal/nodejs-fix-error-connect-econnrefused-1-80-while-using-localhost

Conclusion

Resolving the connect ECONNREFUSED ::1:80 error involves understanding the intricacies of local network configurations and resolving conflicts that prevent the successful connection of your Node.js application. By implementing the suggested troubleshooting steps and potential fixes, developers can overcome this error, ensuring uninterrupted progress in their development environment.

We hope this guide helps you tackle the connect ECONNREFUSED ::1:80 error, enabling you to focus on building your Node.js applications without connectivity hurdles during local development.

Stay tuned for more insightful troubleshooting tips and solutions!

Top comments (0)