Home > Software engineering >  I'm trying to connect to the DB, but the connect() function doesn't seem to work
I'm trying to connect to the DB, but the connect() function doesn't seem to work

Time:09-11

const express = require('express')
const app = express()
// const mysql = require('mysql')
const mysql = require('./db')()
const cors = require('cors')
require('dotenv').config(); 
const port = process.env.PORT || 5000

app.use(express.json())
app.use(cors())

app.listen(port, () => console.log(`${port}`))

app.get('/', (req, res) => {
  res.send("hi")
})

const connection = mysql.init()
mysql.open(connection)

This is my server.js code.

const mysql = require('mysql')
require('dotenv').config(); 

module.exports = function() {
  return {
    init: function () {
      return mysql.createConnection({
        host: process.env.HOST,
        user: process.env.USER,
        password: process.env.PASSWORD,
        database: process.env.DATABASE,
        port: process.env.PORT
      })
    },

    open: function(con) {
      con.connect(function(err) {
        // if (err) throw err
        // console.log('Connected!')
        if(err) {
          console.log('mysql connection error: ' err)
        } else {
          console.log('mysql is connected successfully.')
        }
      })
    }
  }
}

And this is my db.js code...
I expect the port number and message "mysql is connected successfully" to be printed when this code is executed. But when I run it, nothing is output except for the port number. Even an error message.
So I can't verify that the database connection was made properly. Why is the contents of the connect() function not executed?

What is output to the console when the code is executed

CodePudding user response:

You have used same environment variable for server port and database port. Please change variable name PORT of database port to DB_PORT in .env file. Then change the environment variable name in the database port of db.js file as well.

db.js

const mysql = require("mysql");
require("dotenv").config();

module.exports = function () {
  return {
    init: function () {
      return mysql.createConnection({
        host: process.env.HOST,
        user: process.env.USER,
        password: process.env.PASSWORD,
        database: process.env.DATABASE,
        port: process.env.DB_PORT,
      });
    },

    open: function (con) {
      con.connect(function (err) {
        // if (err) throw err
        // console.log('Connected!')
        if (err) {
          console.log("mysql connection error: "   err);
        } else {
          console.log("mysql is connected successfully.");
        }
      });
    },
  };
};

example .env file

PORT=8080
HOST=localhost
USER=root
PASSWORD=root
DATABASE=dbname
DB_PORT=3306
  • Related