I’m losing my mind on this one. I have my app.js
which creates a connection to mysql. It works fine like this :
app.js
const path = require('path') const hbs = require('hbs') const express = require('express') const mysql = require('mysql') const app = express() const port = process.env.PORT || 3000 const db = mysql.createConnection({ host: "localhost", user: "root", password: "password", database: "test" }); db.connect((error) => { if(error) throw error console.log("MYSQL Connected") })
But it doesn’t work with this :
app.js
const path = require('path') const hbs = require('hbs') const express = require('express') const dotenv = require('dotenv') const mysql = require('mysql') dotenv.config({ path: './.env' }) const app = express() const port = process.env.PORT || 3000 const db = mysql.createConnection({ host: process.env.HOST, user: process.env.USER, password: process.env.PASSWORD, database: process.env.DATABASE }); db.connect((error) => { if(error) throw error console.log("MYSQL Connected") })
.env
DATABASE = test HOST = localhost USER = root PASSWORD = password
It recognizes the values I have stored in my .env file since my IDE is showing me the values when I type them in and as long the values of user & password are typed in app.js (but not host and database), it works.
I’m new to MySQL, never used it before, and I’m on Windows. So if I need to do some command lines, can you please specify in which terminal I should type them in ?
Can someone help me ?
Thank you !
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Found the answer.
For some reason, this path :
dotenv.config({ path: './.env' })
Didn’t work. I had to do it like this :
const path = require('path') const dotenv = require('dotenv') dotenv.config({ path: path.join(__dirname, './.env') })
I found this solution by using console.log()
on the variables (process.env.HOST, etc…). They were undefined.
Conclusion : always console.log()
your stuff.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0