I keep getting a ECONNREFUSED error when trying to start my server.
Anyways, here is the full error I received, and afterwards my index.js code:
Error: connect ECONNREFUSED 127.0.0.1:3306
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1606:16) {
errno: -111,
code: ‘ECONNREFUSED’,
syscall: ‘connect’,
address: ‘127.0.0.1’,
port: 3306,
fatal: true
const express = require("express");
const mysql = require("mysql2");
const app = express();
const PORT = process.env.PORT || 3001;
app.use(express.json());
var db = mysql.createConnection({
host: '127.0.0.1',
user: 'root',
password: 'mypw',
database: 'mydb',
port: '3306',
});
// db.connect((err) => {
// if (err) {
// console.error("Error connecting to MySQL:", err);
// return;
// }
// console.log("Connected to MySQL database");
// });
db.connect((err => {
if (err) throw err;
console.log('MySQL Connected');
}));
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
// Followed by CRUD operations for database
I’ve tried using localhost initially as my ‘host’, and even tried using socketPath too. I also tried using mysql instead of mysql2. I think the error could lie in the fact that my port 3306 is already taken up by my computer beforehand. Not sure if it helps, but my XAMPP Control Panel earlier had an error that said my port 3306 is already being used, though it no longer shows that error now.
I also tried the following for mysql admin:
create user ‘root’@localhost IDENTIFIED BY ‘password’;
GRANT ALL PRIVILEGES ON . TO ‘root’@’localhost’ WITH GRANT OPTION;
the first one gave an error, while the second one modified 0 lines.
Before all this, I tried running the server with this code:
const express = require('express')
const app = express()
const mysql = require('mysql')
const cors = require('cors')
app.use(express.json())
app.use(cors())
app.listen(3305, () => {
console.log('Server is running on port 3305')
})
const db = mysql.createConnection({
user : 'root',
host: 'localhost:3305',
password: 'Shishir040204',
database : 'roameo',
})
app.get('/', (req, res) => {
res.json({message:"ok"})
})
app.post('/', (req, res) => {
const sentEmail = req.body.EMAIL
const sentUserName = req.body.USERNAME
const sentPassword = req.body.PASSWORD
const SQL = 'INSERT INTO users (EMAIL, USERNAME, PASSWORD) VALUES (?, ?, ?)'
const Values = [sentEmail, sentUserName, sentPassword]
db.query(SQL, Values, (err, results) => {
if(err) {
res.send(err)
}
else {
console.log('User inserted successfully')
res.send({message: 'User added!'})
}
})
})
Now this did run the server, and I got the message ‘ok’ on the port, but my database was not connected to it. Any information I added did not get added to the database
cozmik is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.