node.js mysqlエラー「Client does not support authentication protocol requested by server; consider upgrading MySQL client」の原因と対処法

node.js mysqlエラー「Client does not support authentication protocol requested by server; consider upgrading MySQL client」の原因と対処法

node.jsのライブラリ「mysql」でmysql8に接続時に、rootでうまく接続できなかったので原因と対処法記述してます。

環境

  • OS  CentOS Linux release 8.0.1905 (Core)
  • node V14.15.1
  • npm 6.14.8
  • nodeモジュール mysql 2.18.1
  • mysql 8.0.20-11

エラー全文

  code: 'ER_NOT_SUPPORTED_AUTH_MODE',
  errno: 1251,
  sqlMessage: 'Client does not support authentication protocol requested by server; consider upgrading MySQL client',
  sqlState: '08004',
  fatal: true

原因

ライブラリ「mysql」がmysql8に対応してないため

対処法

パスワードの認証方式を「mysql_native_password」に変更する

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'パスワード';

ユーザーごとの認証方式は以下のクエリで確認可能です。

select USER,plugin from mysql.user;