node.jsexpressdatabase-connectionmysql2

Access Denied Error When Trying to Insert Data into MySQL Database Using Express and Connection Pool


I'm encountering an issue while trying to insert new data into my MySQL database using Express and a connection pool. Each time I click the submit button on my website, I receive the following error message: Error: Access denied for user ''@'localhost' (using password: NO)

Here's the relevant code snippet from my Node.js application server.js:

import express from "express";
import cors from "cors";
import dotenv from "dotenv";
import * as mysql from "mysql2";
dotenv.config({ path: "backend/server/.env" });
import { saveNewBirthday } from "./database/saveNewBirthday.js";

const server = express();
const corsOption = {
  origin: "http://localhost:3000",
};

const port = 8000;
server.use(cors(corsOption));
server.use(express.json());
const pool = mysql.createPool({
  host: process.env.DB_HOST,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
});

server.post("/new_birthday", (req, res) => {
  const requestBody = req.body;
  const date = requestBody.date;
  const name = requestBody.name;
  const memo = requestBody.memo;
  const sendEmail = requestBody.sendEmail;
  
  saveNewBirthday(pool, date, name, memo, sendEmail) //
    .then((result) => {
      console.log(result);
    })
    .catch((reject) => {
      console.log(reject);
    });
});
server.listen(port, () => {
  console.log("listening on", port);
})

And it's saveNewBirthday function code from saveNewBirthday.js:

export function saveNewBirthday(pool, date, name, memo, sendEmail) {
 return new Promise((resolve, reject) => {
   pool.getConnection((error, connection) => {
     if (!error) {
       const query =
         "INSERT INTO birthdays (BirthDate, BirthName, BirthMemo, SendEmail) VALUES (?, ?, ?, ?)";
       const data = [date, name, memo, sendEmail];
       connection.query(query, data, (err) => {
         if (!err) {
           connection.release();
           resolve({
             fail: false,
             where: "",
             errorMessage: "",
           });
         } else {
           reject({
             fail: true,
             where: "insert",
             errorMessage: `${err}`,
           });
         }
       });
     } else {
       reject({
         fail: true,
         where: "getConnection",
         errorMessage: `${error}`,
       });
     }
   });
 });
}

I've verified that process.env.DB_PASSWORD is correctly loaded, and the MySQL user has all the necessary privileges. Despite these checks, the access denied error persists.

Can someone help me understand why I'm encountering this issue and suggest potential solutions? I appreciate any insights or guidance.


Solution

  • If using ES Module import syntax as opposed to the CommonJS require() function you need to understand what is being exported from the module and how the authors expect you to use the module.

    Change this:

    import dotenv from "dotenv";
    

    to this:

    import 'dotenv/config'
    

    Note: the .env file needs to be in the root directory of your project. If it isn't and you can't/won't move it then you will need to do something like:

    import * as dotenv from 'dotenv';
    dotenv.config({ path: "path/to/your/.env" })