0

I am connecting a MySQL database to my NODEJS application. there is an error every time I start the server, Access denied for user 'root'@'localhost' using password YES, error number 1045

I've found that a lot of developers have asked the same question, yet neither of them had the same answer, and I've done all that I have found. I tried releasing the connection, restarting phpMyAdmin, dropping users and databases that have the same hostname. The versions of node, express, mysql, mysqljs are the latest versions. And looked for about 6 hours at the code trying to find any syntax error in js or sql.

const http = require('http');
const express = require('express');

const path = require('path');

const mysql = require('mysql');
const port = process.env.port || 3000;
const db = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: 'nodemysql'
    //port: port
});

db.connect((err) => {
    if (err) {
        console.log('error when connecting to db:', err);
        throw err;
    }
    console.log('MySql is Connected');
});

const app = express();

app.get('/profile', (req, res) => {

    console.log(result);
    res.sendFile(path.join(__dirname + '/profile.html'));
});

app.get('/createdb', (req, res) => {
    let sql = 'CREATE DATABASE nodemysql';
    db.query(sql, (err, result) => {
        if (err) {
            throw err;
        }
    })

});
//app.use(express.json());

app.listen(port, () => console.log(`listening on port ${port}...`));

and the package.json looks like this:

  {
   "name": "community",
   "version": "1.0.0",
   "description": "",
     "main": "app.js",
     "scripts": {
       "test": "echo \"Error: no test specified\" && exit 1"
     },
     "author": "Omar AbdelFattah",
     "license": "ISC",
     "dependencies": {
       "express": "^4.16.4",
       "mysql": "^2.17.1",
       "mysqljs": "0.0.2-security"
     }
   }

The expected output is if I run 'nodemon app.js' or 'node app' or whatever, in the terminal, the server will run and then I use one of the two endpoints to open display the HTML file or connect to the database.

The actual results are an error occurs: 'Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'root'@'localhost' (using password: YES)' BUT the server runs! and the 'app.listen()' function is executed.

1 Answers1

0

Error #1045 either gets outputted when the user does not have privileges for the database (unlikely as you are root and localhost) or when the password is wrong. The listen event will get called anyway, the way this flow is structured a failed database connection only throws an error, it doesn't stop the server.
You could try resetting your root password (from terminal if possible) just to be sure before searching for deeper issues.

Dejan
  • 21
  • 4