skip to Main Content

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


  1. I connect NodeJS con MySQL/MariaDB using sequelize package, this code is with typescript, you must change imports to require.

    import { Sequelize } from 'sequelize';
    
    // -----------------------------------------------------
    const sequelize = new Sequelize('node', 'username', 'your-password', {
        host: 'localhost',
        dialect: 'mysql',
        // logging: false
        /* one of 'mysql' | 'postgres' | 'sqlite' | 'mariadb' | 'mssql' | 'db2' | 'snowflake' | 'oracle' */
      });
      // -----------------------------------------------------
    
      export default sequelize;
    

    //——————————————————

    // Then in the server I have this code.

    import express, { Application } from 'express';
    import cors from "cors";
    
    import userRoutes from '../routes/usuario.mjs';
    import sequelize from '../db/connection.mjs';
    
    class Server {
        private app: Application;
        private port: string;
        private apiPath ={
            usuarios: '/api/usuarios'
        }
    
        // -----------------------------------------------------
        constructor(){
            this.app = express();
            this.port = process.env.PORT || '8000';
    
            // connect to DB
            this.dbConnection();
           // ...
    
        }
        // -----------------------------------------------------
        // Connect with DB
        async dbConnection(){
            try {
                await sequelize.authenticate();
                console.log('Database is connected.');
            } catch (error: any) {
                throw new Error( error.message );
            }
        }
    }
    

    It works porperly for my.

    Login or Signup to reply.
  2. 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.

    {
      "development": {
        "username": "root",
        "password": "123456",
        "database": "your db",
        "host": "127.0.0.1",
        "dialect": "mysql",
        "query": {
          "raw": true
        },
        "options": {
          "pool": {
            "max": 5,
            "min": 0,
            "acquire": 30000,
            "idle": 10000
          }
        }
      },
    {
      "development": {
        "username": "root",
        "password": "123124",
        "database": "yourDB",
        "host": "127.0.0.1",
        "dialect": "mysql",
        "query": {
          "raw": true
        },
        "options": {
          "pool": {
            "max": 5,
            "min": 0,
            "acquire": 30000,
            "idle": 10000
          }
        }
      },
    
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search