跟进:ECONNREFUSED 127.0.0.1:3306 错误将 MySQL 数据库连接到 NodeJS express 服务器(带打字稿),我通过将问题缩小到“通过终端运行应用程序而不是 coderunner 扩展(其中有效,但仅适用于单个文件,而不是构成目录并一起运行的分散文件)。”
这是我通过终端运行时遇到的问题,即 node/nodemon
Error: connect ECONNREFUSED 127.0.0.1:3306
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16)
--------------------
at Protocol._enqueue (/mnt/c/Users/abdul/Desktop/nodemysql/node_modules/mysql/lib/protocol/Protocol.js:144:48)
at Protocol.handshake (/mnt/c/Users/abdul/Desktop/nodemysql/node_modules/mysql/lib/protocol/Protocol.js:51:23)
at Connection.connect (/mnt/c/Users/abdul/Desktop/nodemysql/node_modules/mysql/lib/Connection.js:116:18)
at Object.<anonymous> (/mnt/c/Users/abdul/Desktop/nodemysql/app.js:13:4)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47 {
errno: -111,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 3306,
fatal: true
}
下面是我用来连接到 MySQL 数据库的新代码(请记住,由于某种原因它可以与 coderunner 扩展一起使用,而不是 node / nodemon)
const express = require("express");
const mysql = require("mysql");
// Create connection
const db = mysql.createConnection({
host: "localhost",
user: "root",
port: 3306,
password: "password",
});
db.connect((err) => {
if (err) {
throw err;
}
console.log(" ... CONNECTED ... ");
});
const app = express();
app.get("/createdb", (req, res) => {
let sql = "CREATE DATABASE nodemysql";
db.query(sql, (err, result) => {
if (err) throw err;
console.log(result);
res.send({
message: "this is the result: " + result,
});
db.end();
});
});
app.listen("3000", () => {
console.log("Server started on port 3000");
});
有任何想法吗?