nodejs - - - - - nodejs connection database error: client-does-not-support-authentication-protocol-requested-by-server

Link database error: client-does-not-support-authentication-protocol-requested-by-server

1. The code is as follows

// 1. 导入 mysql 模块
const mysql = require("mysql");
// 2. 建立与 MySQL 数据库的连接关系
const db = mysql.createPool({
    
    
  host: "127.0.0.1", // 数据库的 IP 地址
  user: "root", // 登录数据库的账号
  password: "root@123", // 登录数据库的密码
  database: "weixin", // 指定要操作哪个数据库 // 如果没提前创建数据库,会报错 ER_BAD_DB_ERROR: Unknown database 'weixin'
});

// 测试 mysql 模块能否正常工作
db.query("select 1", (err, results) => {
    
    
  // mysql 模块工作期间报错了
  if (err) return console.log("出错了=====>", err.message);
  // 能够成功的执行 SQL 语句
  console.log("查询结果", results);
});

Execute the script, but encountered the following error
Client does not support authentication protocol requested by server

2. Solutions

After querying the data, I found that it seemed to be related to the mysql version, and then I started searching for a solution.
MySQL8.0版本的加密方式和MySQL5.0的不一样,连接会报错。

The solution is as follows:

  • login database
    /usr/local/mysql/bin/mysql -u root -p
  • Enter root's password
    Enter password: ******
  • Change the encryption method (copy it to the command window as it is)
    mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'password' PASSWORD EXPIRE NEVER;
  • Change password: root@123 is the new password in this example
    mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'root@123';
  • Refresh:
    mysql> FLUSH PRIVILEGES;
    insert image description here

Execute the script again to link to the database, and encounter the following error
ER_ACCESS_DENIED_ERROR: Access denied for user ‘root‘@‘localhost‘(using password: YES)

Cause:
The login password has just been changed in the terminal, but it is not updated in the script

Guess you like

Origin blog.csdn.net/Dark_programmer/article/details/131062115