I'm trying to create a log system with MySQL and Node.JS. But I'm getting the error you see below, I'm still actively looking for a solution, but I couldn't find it. And I decided to ask you.
.env
DB_HOST = 127.0.0.1
DB_USER = newuser
DB_PASSWORD = password123#
DB_DATABASE = userDB
DB_PORT = 3306
PORT = 3000
Node.js
const express = require('express');
const app = express();
const mysql = require('mysql');
require('dotenv').config({path: './dbInfo.env'})
const db = mysql.createPool({
connectionLimit: 100,
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
port: process.env.DB_PORT
})
db.getConnection( (err, connection) => {
if (err) throw (err)
console.log("DB connected succesful:" + connection.threadId)
})
const port = process.env.DB_PORT
app.listen(port,
() => console.log('Server started on port ${port}...'))
console.log(process.env.DB_PASSWORD)
It seems the Port 3306 is already used. 3306 is the MySQL standard port, so most likely your MySQL instance is already running which you would want.
You can only have one service running behind a port. That's the purpose of ports to direct traffic to the process that can deal with that traffic or expects that traffic.
To resolve the issue use const port = process.env.PORT
instead of const port = process.env.DB_PORT
. Your Express server then runs on port 3000
and your MySQL server on port 3306
.
FYI: You should specify some default values (or errors) in case the environment variables are not set. You might have set them here with your .env
file both you might wanna run the server in another environment some day and you'll forget to configure something and wonder why your server is crashing.
One quick and easy solution that will do for starters could be to use logical OR (||
). This will set the port set in the environment variables or the default value of 3000
.
// Mocking process.env
const process = { env: {}}
// process.env.PORT is not defined here so the default value will be used
const port = process.env.PORT || 3000;
console.log(`Port: ${port}`)
You might also be interested in the dotenv npm package.