使用Node.js连接到MySQL

我打算在之前的文章中完成的AWS上的MySQL上,尝试使用Nodejs进行连接确认。
在上次之前的文章中,已经在AWS上的CentOS上建立了Nodejs执行环境。

代码准备

将以下内容放置在任意项目中:
const connection以下,填入MySQL设置的用户和密码、数据库名称。

应用程序.js / 应用.js

const express = require('express');
const mysql = require('mysql');
const app = express();

app.use(express.static('public'));
app.use(express.urlencoded({extended: false}));

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'Passw0rd!',
  database: 'list_app'
});

connection.connect((err) => {
  if (err) {
    console.log('error connecting: ' + err.stack);
    return;
  }
  console.log('success');
});

app.get('/', (req, res) => {
  connection.query(
    'SELECT * FROM items',
    (error, results) => {
      console.log(results);
      res.render('hello.ejs');
    }
  );
});

app.listen(3000);

你好。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Hello World</title>
    <script src="/send_url.js"></script>
  </head>
  <body>
    <h1>Hello World</h1>
  </body>
</html>

启动项目 ( )

发生了一个错误,提醒您需要更新MySQL客户端…

# node app.js
error connecting: Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requestd by server; consider upgrading MySQL client
    at Handshake.Sequence._packetToError (/data/proj/node_modules/mysql/lib/protocol/sequences/Sequence.js:4:14)

当我进行调查时,发现了这篇文章。

 

为了先解决问题,我尝试更改了认证插件。

mysql> SELECT user, host, plugin FROM mysql.user;
+------------------+-----------+-----------------------+
| user             | host      | plugin                |
+------------------+-----------+-----------------------+
| prog01           | %         | caching_sha2_password |
| mysql.infoschema | localhost | caching_sha2_password |
| mysql.session    | localhost | caching_sha2_password |
| mysql.sys        | localhost | caching_sha2_password |
| root             | localhost | caching_sha2_password |
+------------------+-----------+-----------------------+
5 rows in set (0.00 sec)

mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'Passw0rd!';
mysql> SELECT user, host, plugin FROM mysql.user;
+------------------+-----------+-----------------------+
| user             | host      | plugin                |
+------------------+-----------+-----------------------+
| prog01           | %         | caching_sha2_password |
| mysql.infoschema | localhost | caching_sha2_password |
| mysql.session    | localhost | caching_sha2_password |
| mysql.sys        | localhost | caching_sha2_password |
| root             | localhost | mysql_native_password |
+------------------+-----------+-----------------------+
5 rows in set (0.00 sec)

成功连接到数据库。

[root@ip-172-31-1-181 proj]# node app.js
success
广告
将在 10 秒后关闭
bannerAds