Home > Blockchain >  Problem connecting express and MySQL azure
Problem connecting express and MySQL azure

Time:12-30

I'm new using Azure, I've created my database server and I'm trying to connect using environment variables. When doing a simple SQL query to check that I'm connected I get the following error:

Error: Access denied for user ''@'localhost' (using password: NO)
  code: 'ER_ACCESS_DENIED_ERROR',
  error: 1045,
  sql:undefined,
  sqlState: '28000',
  sqlMessage: "Access denied for user ''@'localhost' (using password: NO)"

index.js

import express from "express";
import {PORT} from "./config.js";
import indexRoutes from './routes/index.routes.js'

const app = express();

app.use(indexRoutes);
app.listen(PORT);

console.log(`Server listening on port ${PORT}`);

config.js

import dotenv from 'dotenv'

dotenv.config()

export const config = {
    db: {
        host: process.env.HOSTNAME,
        user: process.env.USER,
        password: process.env.PASSWORD,
        database: process.env.DATABASE,
        port: process.env.PORT
    }
};


export const PORT = 4000;

index.routes.js

import { Router } from "express";
import { pool } from "../db.js";

const router = Router();

router.get("/ping", async (req, res) => {
  const result = await pool.query("SELECT 1   1 as result");
  console.log(result);
  res.json("ping");
});

export default router;

db.js

import {createPool} from 'mysql2/promise';


export const pool = createPool({

});


CodePudding user response:

you should use ORMs like sequelize or typeorm to perform database interaction using express they make your life very easy

CodePudding user response:

  • Here I was able to run query using mysql2 where I first read the variables separately and then added them to createpool function.
require('dotenv').config();

var  data_base = process.env.d; ;
var  host = process.env.h; ;
var  port = process.env.p;
var  user = process.env.u;
var  pass_word = process.env.pass;

const  mysql = require('mysql2');
const  pool = mysql.createPool({
    host : host,
    database : data_base,
    user : user, 
    password : pass_word,
    port : port
});
const  pro = pool.promise();
const [rows,fields] = await  pro.query("CREATE TABLE testtt (P int)");

output:

enter image description here

  • Also, I think this can be a credential issue check the password and user.
  • Related