node.js连接数据库的坑
端口问题的坑。
error connecting: Error: ER_ACCESS_DENIED_ERROR: Access denied for user ‘root’@‘DESKTOP-NLN1UTH’ (using password: YES)
const mysql = require("mysql");
// 连接信息
const connection = mysql.createConnection({
host: '192.168.1.200',
user: 'root',
password: '123456',
database: 'mysql',
post: '3310',
});
// 建立连接
// connection.connect();
connection.connect(function (err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
不知道大家有没有注意到,上面的port被打错为post。但是因为是key,value的格式,所以没有报错。
webstrom连接以后报错为下面内容。
error connecting: Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'root'@'DESKTOP-NLN1UTH' (using password: YES)
at Handshake.Sequence._packetToError (G:\myworkspace\fontWorkspace\ossdownload\node_modules\mysql\lib\protocol\sequences\Sequence.js:47:14)
at Handshake.ErrorPacket (G:\myworkspace\fontWorkspace\ossdownload\node_modules\mysql\lib\protocol\sequences\Handshake.js:123:18)
at Protocol._parsePacket (G:\myworkspace\fontWorkspace\ossdownload\node_modules\mysql\lib\protocol\Protocol.js:291:23)
加密规则的坑(docker启动)
因为mysql我是用docker启动的。版本为mysql8.0.16。启动命令用的是。
docker run -d -e MYSQL_ROOT_PASSWORD=12345678 -p 3310:3306 --name dbmysql --restart always -v E:/docker/container/mysql11:/var/lib/mysql mysql
上面命令可以启动,用webstrom连接会报如下错误。
error connecting: Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client
at Handshake.Sequence._packetToError (G:\myworkspace\fontWorkspace\ossdownload\node_modules\mysql\lib\protocol\sequences\Sequence.js:47:14)
at Handshake.ErrorPacket (G:\myworkspace\fontWorkspace\ossdownload\node_modules\mysql\lib\protocol\sequences\Handshake.js:123:18)
因为node.js提供的mysql包中的加密方式为caching_sha2_passwod。node.js连接的加密方式为mysql_native_password。通常的修改方法为。
ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY '12345678';
flush privileges;
但是本来我都用docker启动了。就是为了方便爽。这样搞就很麻烦。所以干脆点,用下面docker命令启动。多了一行这个–default-authentication-plugin=mysql_native_password 。这就让我的root用户启动时候,加密方式就变了。我觉得nodejs的mysql的包,应该修复一下这个错误,因为对新手很不友好啊。
docker run -d -e MYSQL_ROOT_PASSWORD=123456 -e MYSQL_DATABSE=db -p 3310:3306 --name dbmysql --restart always -v E:/docker/container/mysql11:/var/lib/mysql mysql --default-authentication-plugin=mysql_native_password