简体   繁体   中英

I can't connect to mysql database using process.env.variable

my config.env file

PORT=5000
DB_HOST='localhost'
DB_PORT=3306
DB_USER='root'
DB_PASSWORD='fast'
DB_NAME='hms'

my dbconnect file(in same directory as config.env file) I cannot connect using process.env but if I directly type values like I have did in commented code then it will connect to database. Also if I console.log values of process.env.anyvariable then I will get the correct value of env variable but if i assign it to some variable like suppose const variable=process.env.DB_HOST then it will be undefined in console.log. It is throwing me this error

code: 'ER_ACCESS_DENIED_ERROR',
  errno: 1045,
  sqlMessage: "Access denied for user ''@'localhost' (using password: NO)",
  sqlState: '28000',
  fatal: true

const mysql = require("mysql")
const dotenv = require("dotenv")

dotenv.config({ path: './config.env' });

const connection = mysql.createConnection({
    host: process.env.DB_HOST,
    port: process.env.DB_PORT,
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME
})

// const connection = mysql.createConnection({
//     host: 'localhost',
//     port: 3306,
//     user: 'root',
//     password: 'fast',
//     database: 'hms'
// })

connection.connect( (err) => {
    if (err){
        console.log(err)
    }
    else
    {
        console.log("Database connected!")
    }
})

my /config/config.env is not in the parent directoy so instead of

dotenv.config({ path: './config.env' });

write

dotenv.config({ path: __dirname + '/config.env' });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM