[Node] When using Node.js to connect to the database, an error occurs. The client does not support the authentication protocol requested by the server.

Error when connecting to database using Node.js

Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client

This is caused by Node not supporting MySQL version 8.0 or above for the time being. There are two solutions.

1. Lower the MySQL version,

This operation is relatively simple. Just go to the official website and download it again. I won’t go into too much detail here about the MySQL official website.

2. Use CMD to connect to the database

Here we mainly explain this method

mysql -u root -p
Enter password: ******

The asterisk is your password.
Enter this line of command after logging in successfully.

 ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '123456';

The 123456 here is my password, just replace it with your own.
Finally, refresh the permissions.

 FLUSH PRIVILEGES;

Just use Node.js to connect again.
Finally, let me show you my code.

//1: 导入mysql依赖包,  mysql属于第三方的模块就类似于 java.sql一样的道理
const {
    
     Console } = require("console");
var mysql=require("mysql");
// 1: 创建一个mysql的Connection对象
// 2: 配置数据连接的信息 
var connection = mysql.createConnection({
    
    
    host:"127.0.0.1",
    user:"root",
    port:3306,
    password:"123456",
    database:"testdb"
})
// 3:开辟连接
connection.connect();
// 4: 执行curd
connection.query("select * from kss_user",function(error,results,fields){
    
    
    //如果查询出出错,直接抛出
    if(error){
    
    
        throw error;
    }
    //查询成功
    console.log("results = ",results);
});
// 5: 关闭连接
connection.end();
// 最后一步:运行node db.js 查看效果

Guess you like

Origin blog.csdn.net/Daears/article/details/126947189