I am able to connect via the mySQL shell, but when I try from VS Code Nodemon crashes and i get the error.
code: ‘ER_ACCESS_DENIED_ERROR’,
errno: 1045,
sqlMessage: "Access denied for user ‘root’@’localhost’ (using password: YES)",
sqlState: ‘28000’,
fatal: true
My environment variable path is set up.
I have run… ALTER USER ‘root’@’localhost’ IDENTIFIED WITH mysql_native_password BY ‘123456’
I have set up a new user, granted them full permissions and tried to connect to that user but still denied access.
//server.js
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
var mysql = require('mysql');
const app = express();
app.use(cors());
app.use(bodyParser.json());
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '123456'
});
db.connect((err) => {
if(err){
console.log(err);
} else {
console.log('Connected');
}
})
app.listen('8000', () => console.log("Server running on port 8000"));```
package.json
{
"name": "mern-prac-2-backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.20.1",
"cors": "^2.8.5",
"express": "^4.18.2",
"mysql": "^2.18.1",
"nodemon": "^2.0.20"
}
}
Thanks!
(edited)
Based on Juans Answer I have changed to this...
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const {Sequelize} = require('sequelize');
const app = express();
app.use(cors());
app.use(bodyParser.json());
const sequelize = new Sequelize('fake_company', 'root', '123456', {
host: 'localhost',
dialect: 'mysql',
});
const tryConnection = async () => {
try {
await sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
}
}
tryConnection();
app.listen('8000', () => console.log("Server running on port 8000"));
And am having the error ...
code: 'ER_ACCESS_DENIED_ERROR',
errno: 1045,
sqlState: '28000',
sqlMessage: "Access denied for user 'root'@'localhost' (using password: YES)",
sql: undefined
3
Answers
I connect NodeJS con MySQL/MariaDB using sequelize package, this code is with typescript, you must change imports to require.
//——————————————————
// Then in the server I have this code.
It works porperly for my.
If you want to use sequelize, I think you can create the perfect configuration with sequelize init commands. Sequelize gives you a config file in a configuration folder like below. You have to define a database for sequelize don’t forget that.
Firstly you have to install npm install –save-dev sequelize-cli for your cli commands.Then you can use sequelize init command.
I think creating a new user and giving it privilege will help. The root user might need root access or administrative access. And node doesn’t have a root access.