0

I am using node.js, mysql, ejs (templating engine) and bootstrap to create a website. I have tried to connect to mysql database by creating a connection (as seen in the code).

When i use nodemon, the first message that I get is that the server is connected on port 8089. However, the site does not connect to the sql database straight away. I have to restart nodemon (by pressing save) and then the site is connected to the database.

I am looking for a method which connects the site to the database on the first attempt when running nodemon.

const db = mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
database: "MyFood"
});

db.connect((err) => {
if (err) {
    // throw err;
    console.error("error connecting: "  + err.stack);

} else {
    console.log("Connected to database");
}
});

global.db = db;
Serg
  • 2,346
  • 3
  • 29
  • 38
romi
  • 1
  • What exactly is your issue? Please explain the problem clearly. – jaimish11 Aug 02 '20 at 13:26
  • i am using node.js, mysql, ejs (templating engine) and bootstrap to create a website. I have tried to connect to mysql database by creating a connection (as seen in the code). When i use nodemon, the first message that i get is that the server is connected on port 8089. However, the site does not connect to the sql database straight away. i have to restart nodemon (by pressing save) and then the site is connected to the database. I am looking for a method which connects the site to the database on the first attempt when running nodemon. – romi Aug 02 '20 at 13:44
  • Can you give more details regarding your file structure and where exactly this piece of code is written i.e in which file. – jaimish11 Aug 02 '20 at 15:03
  • **server is connected on port 8089** this log message is that you already started the server so you have to kill process that is listening on port 8089 [ref](https://stackoverflow.com/questions/31649267/how-to-kill-a-nodejs-process-in-linux) – meBe Aug 03 '20 at 15:32
  • Also if you see the log **Connected to database** than why should it be a issue? – meBe Aug 03 '20 at 15:34

0 Answers0