I am attempting to connect to mySQL through a NodeJS file, but I receive the following error:
{ Error: ER_ACCESS_DENIED_ERROR: Access denied for user \'root\
The code to connect to mysql using dotenv in nodejs
.env file
NODE_ENV=DEVELOPMENT
DB_HOST=localhost
DB_USER=root
DB_PASSWORD=password
DB_NAME=test
db.js file
const util = require("util");
const mysql = require("mysql2");
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database : process.env.DB_NAME,
uri: process.env.DB,
waitForConnections: true,
connectionLimit: 10,
queueLimit: 2,
});
The problem is not with the mysql user authentication. It just that you have to grant your node application to access mysql db. I was facing the same issue earlier.I added the port number on which my node application is running.And its working perfectly fine now.
Also user:"root" was written as username:"root" . Be careful with the spellings.
const mysqlConnection = mysql.createConnection({
host: "localhost",
user: "root",
password: "Pass@123",
database: "employees",
port:"3000",
multipleStatements: true
});
I am using mysql version "mysql": "^2.18.1".
Mostly the issue will be with the way the password entered is interpreted by MySQL server. Please follow the below link. It should resolve the issue. MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client
uninstall mysql,and uninstall mysql related service(eg. mysqld.exe xampp).then,reinstall mysql.
If anyone is still facing problem. Try
var mysql = require("mysql");
var con = mysql.createConnection({
host: "127.0.0.1",
user: "your_username",
password: "password",
database: "your_db_name"
});
//surprisingly this works.
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: ""
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});