Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node JS and mysql not connecting (client does not support authentication protocol requested by server consider upgrading mysql client)

I'm trying to connect my NodeJs application with a mysql database but its not connecting for some reason.

I did install the mysql npm like this (typed this in commandline):

npm install mysql

After I installed the mysql npm I made an index.js file and in that file I tried to make the connection with my database.

This is the code inside my index.js file to make a connection with mysql:

const mysql      = require('mysql');

var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    port     : '3306',
    password : 'test12310',
    database : 'fys'
});


connection.connect((err) => {
    if(!err)
        console.log('Database is geconnect!');
    else
        console.log('Database connectie niet gelukt!  : '+ JSON.stringify(err, undefined,2));
});

Then I tried to run the code and see if the connection with mysql worked. I typed this in the command line:

node index.js

This is the error message I got in the command prompt :

error image

Does anyone know how I can fix this error and get a connection with my mysqldatabase in nodejs ?

Any kind of help is appreciated

like image 401
johnny Avatar asked Nov 13 '18 14:11

johnny


2 Answers

Use the new mysql2 library instead of mysql in order to use the new authentication method of MySQL 8.0

~ Tested in node version 13.6.0 and MySQL 8.0.21

like image 84
Sebospc Avatar answered Oct 18 '22 23:10

Sebospc


I was having the same problem with mysql library and I fixed that error by changing to mysql2 Library I recommend you to install mysql2

Run

npm install mysql2

Then

import mysql from "mysql2";

OR

const mysql = require("mysql2")

I hope this will work for you!! Good Luck

like image 9
crispengari Avatar answered Oct 19 '22 00:10

crispengari