Solve the problem of connect ECONNREFUSED 127.0. 0.1: 3306 when Node. js uses MySQL

  • 2021-08-03 08:40:18
  • OfStack

Preface

Recently, I wrote a gadget with Node, which requires MySQL database. Now, the most widely used library is mysql. Then, now that ORM is so popular, I might as well go to ORM, just as I won't be able to learn 1, so I found Sequelize. js, the ORM library.

Find a problem

Look at the documentation of Sequelize, so easy, it's done in two minutes ~


import Sequelize from 'sequelize';
let sequelize = new Sequelize('database', 'username', 'password', {
 host: 'localhost',
 port: 3306,
 dialect: 'mysql',
 pool: {
  max: 5,
  min: 0,
  idle: 10000
 }
});
// ... There are still in the back 1 The pile is too lazy to post 

Run 1

SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:3306

What the hell, why did this mistake happen? I clearly set localhost, why did it change to 127.0. 0.1?

Solve a problem

As usual, Google first found that many people also encountered this problem. There are probably several solutions:

1. Do you think you can run without installing MySQL? Go install the database!

2. Is your database running? Quick/etc/init. d/mysqld start

3. The port is written incorrectly

4. Have you turned on the option skip-networking? Remove it!

When I saw this, I reacted, because my database does not involve remote access, so it is enough to use Unix socket communication, so skip-networking is enabled so that MySQL does not listen on the specified port.

What is skip-networking under the first science popularization 1

Do not listen for TCP/IP connections at all. All interaction with mysqld must be made using named pipes or shared memory (on Windows) or Unix socket files (on Unix). This option is highly recommended for systems where only local clients are permitted.

Translation 1 is:

Do not listen for TCP/IP connections. All interactions with mysqld must use named pipes or shared memory (on Windows) or Unix socket files (on Unix). This option is strongly recommended for systems that only allow local clients.

Source

But for the sake of safety, I don't want to remove this option. Do I have to reluctantly use ORM?

Because of the documentation, the mysql connection library can use the socketPath attribute to specify the Unix socket file, but Sequelize. js did not find the attribute.

Finally, I had to send issue, and soon dalao replied that dialectOptions could be used to set the properties of mysql.

The following is the code that tested successfully:


import Sequelize from 'sequelize';
let sequelize = new Sequelize('database', 'username', 'password', {
 host: 'localhost',
 port: 3306,
 dialect: 'mysql',
 dialectOptions: {
  socketPath: '/tmp/mysql.sock' //  Specify the socket file path 
 }
 pool: {
  max: 5,
  min: 0,
  idle: 10000
 }
});

It's as simple as that …

Summarize


Related articles: