I’m encountering an ECONNREFUSED error when attempting to connect to my MySQL database using Node.js. I’ve configured my connection to use the address ‘127.0.0.1’ and port ‘3306’, but the connection is being refused. Here’s a snippet of my code: this error is coming when i try to deploy my project on render.com
my backend code is :
const express = require("express");
const mysql = require("mysql");
const cors = require("cors");
const app = express();
app.listen(8000, (req, res) => {
console.log("connected to backend");
});
const db = mysql.createPool({
connectionLimit: 10,
host: "localhost",
user: "root",
password: "ashabikawat",
database: "expense",
debug: false,
});
db.getConnection((err, connection) => {
if (err) {
console.error("Error connecting to database: " + err.stack);
return;
}
console.log("Connected to database with threadId: " + connection.threadId);
connection.release();
});
app.use(express.json());
app.use(cors());
app.get("/", (req, res) => {
const q = "SELECT * FROM expenses";
db.query(q, (err, data) => {
if (err) return res.json(err);
if (data) return res.json(data);
});
});
app.post("/expenses", (req, res) => {
const q = "INSERT INTO expenses (`text`, `amount`, `type`) VALUES (?)";
const values = [req.body.text, req.body.amount, req.body.type];
db.query(q, [values], (err, data) => {
if (err) return res.json(err);
return res.json("expense created successfully");
});
});
app.delete("/expenses/:id", (req, res) => {
const expenseId = req.params.id;
const q = "DELETE FROM expenses WHERE id = ?";
db.query(q, [expenseId], (err, data) => {
if (err) return res.json(err);
return res.json("expense deleted successfully");
});
});
app.put("/expenses/:id", (req, res) => {
const expenseId = req.params.id;
const q =
"UPDATE expenses SET `text`=? , `amount`= ? , `type` = ? WHERE id = ?";
const values = [req.body.text, req.body.amount, req.body.type];
db.query(q, [...values, expenseId], (err, data) => {
if (err) return res.json(err);
return res.json("expense updated successfully");
});
});
I tried all the things like : Ensured MySQL service was running and listening on port 3306. Attempted connection using both TCP/IP and Unix sockets. Verified the MySQL user permissions and access to the database. Checked the MySQL configuration file (my.cnf) for socket path. Reviewed system logs for any relevant error messages. Tested the setup locally to isolate the issue.