Home >Database >Mysql Tutorial >Node.js MySQL ECONNREFUSED Error: How to Connect Using a Unix Socket?

Node.js MySQL ECONNREFUSED Error: How to Connect Using a Unix Socket?

Susan Sarandon
Susan SarandonOriginal
2024-12-03 11:34:12852browse

Node.js MySQL ECONNREFUSED Error: How to Connect Using a Unix Socket?

Node.js MySQL: Resolving the "ECONNREFUSED" Error When Connecting

When attempting to connect to a MySQL server through Node.js, encountering an "ECONNREFUSED" error can be perplexing, especially when a PHP/Apache server on the same machine operates without any issues.

Let's investigate the cause of this error and provide a solution that has been successful.

The Challenge

In the provided code snippet, the MySQL host is defined as 'localhost', while the MySQL server on the machine listens on a Unix socket '/var/run/mysqld/mysqld.sock' rather than the standard TCP port. This mismatch results in the "ECONNREFUSED" error when the Node.js application attempts to connect using TCP.

The Solution

To resolve this issue, we need to modify the connection options to specify the Unix socket path instead of a TCP port. This can be achieved by adding the following line to the connection options:

port: '/var/run/mysqld/mysqld.sock'

Updated Code

var mysql_link = {
  host: 'localhost',
  port: '/var/run/mysqld/mysqld.sock', // Modified to specify Unix socket path.
  database: 'nodetest',
  user: 'root',
  password: 'xxx'
};

Conclusion

By specifying the correct connection options, we can ensure that the Node.js application is able to establish a successful connection to the MySQL server and continue its operations seamlessly. It's important to verify the configuration of the MySQL server and use the appropriate connection parameters to avoid encountering such errors in the future.

The above is the detailed content of Node.js MySQL ECONNREFUSED Error: How to Connect Using a Unix Socket?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn