'Getting error "connect ECONNREFUSED 127.0.0.1:3306" while connecting to mysql

I'm new to nodeJs and trying to develop my first application. I installed mysql package through npm, It got installed and I can see a successful entry of it in package.json. However, when I'm trying to connect to mysql server, it gives me this error connect ECONNREFUSED 127.0.0.1:3306. I searched for this issue on StackOverflow and the other users who had the very same issue got it running by adding an entry socketPath: '/var/run/mysqld/mysqld.sock' to the configuration object. But when I added this to my configuration object, I got a new error connect ENOENT /var/run/mysqld/mysqld.sock.

Here's the code by which I'm trying to connect to the server

var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'blog',
    socketPath: '/var/run/mysqld/mysqld.sock'
});

connection.connect();
module.exports = router;

I'm using a Windows machine and had mysql installed before via XAMPP package. Can this be the reason behind the connection failure?



Solution 1:[1]

in my case is the docker network that makes the problem.

I add to my docker-compose file: network_mode: "host"

Solution 2:[2]

Check the password inserted, usually it should be "password".

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eylon Koenig
Solution 2 Lotfi Chakchouk