提问人:Asha bikawat 提问时间:11/15/2023 最后编辑:XiduzoAsha bikawat 更新时间:11/15/2023 访问量:34
连接到MySQL数据库时遇到ECONNREJECTED错误(127.0.0.1:3306)
Facing ECONNREFUSED error while connecting to MySQL database (127.0.0.1:3306)
问:
尝试使用 Node.js 连接到我的 MySQL 数据库时,我遇到了 ECONNREFUSED 错误。我已将连接配置为使用地址“127.0.0.1”和端口“3306”,但连接被拒绝。这是我的代码片段: 当我尝试在 render.com 上部署我的项目时,会出现此错误
我的后端代码是:
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: "*****",
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");
});
});
我尝试了所有的事情,例如: 已确保MySQL服务在端口3306上运行并侦听。 尝试使用 TCP/IP 和 Unix 套接字进行连接。 已验证MySQL用户权限和对数据库的访问权限。 已检查MySQL配置文件(my.cnf)中的套接字路径。 已查看系统日志中是否有任何相关错误消息。 已在本地测试设置以隔离问题。
答: 暂无答案
评论
mysql
db.getConnection((err, connection) => {
localhost
hostname
192.168.1.5
myapp.example.com