Node js-mysql运行到ECONNREFUSED错误



js和node的新手,我有一个将查询数据库的app.js,我使用池来查询它,所以我有了一个名为db.js的文件,看起来像这个

const mysql = require('mysql2/promise');
const config = {db: {host: 'localhost',user: 'root',password: '',database: 'school',port:'3308',waitForConnections: true,connectionLimit: 2,queueLimit: 0,},};
const pool = mysql.createPool(config.db);
async function query(sql, params) {
const [rows, fields] = await pool.execute(sql, params);
return rows;
}
module.exports = {query,}

然而,在终端中运行docker compose-build后,我遇到了这个错误

/src/node_modules/mysql2/promise.js:359

test-app-1 | const localErr = new Error();

test-app-1 | ^

test-app-1 |

test-app-1 | Error: connect ECONNREFUSED 127.0.0.1:3308

test-app-1 | at PromisePool.execute (/src/node_modules/mysql2/promise.js:359:22)

test-app-1 | at Object.query (/src/app/services/db.js:20:39)

test-app-1 | at /src/app/app.js:17:8

test-app-1 | at Layer.handle [as handle_request] (/src/node_modules/express/lib/router/layer.js:95:5)

test-app-1 | at next (/src/node_modules/express/lib/router/route.js:137:13)

test-app-1 | at Route.dispatch (/src/node_modules/express/lib/router/route.js:112:3)

test-app-1 | at Layer.handle [as handle_request] (/src/node_modules/express/lib/router/layer.js:95:5)

test-app-1 | at /src/node_modules/express/lib/router/index.js:281:22

test-app-1 | at Function.process_params (/src/node_modules/express/lib/router/index.js:341:12)

test-app-1 | at next (/src/node_modules/express/lib/router/index.js:275:10) {

test-app-1 | code: 'ECONNREFUSED',

test-app-1 | errno: -111,

test-app-1 | sql: undefined,

test-app-1 | sqlState: undefined,

test-app-1 | sqlMessage: undefined

test-app-1 | }

不需要数据库打开的请求很好,例如http://127.0.0.1:3000/但是那些查询数据库的人就陷入了这个错误。我可以看到错误源于模块中的一个文件,但我不知道如何解决这个问题。我的app.js文件中的请求代码看起来像这个

app.get("/", function(req, res) {
res.send("Main Page");});
app.get('/class', function(req,res) {
var sql = 'SELECT * FROM class ';
db.query(sql).then(results => {
console.log(results);
res.json(results);});})

我的index.js文件看起来像这个

"use strict";
console.log("entrypoint");
const app = require("./app/app.js");

我注意到这个错误源于一个模块文件,但由于我缺乏经验,我不想篡改它。

由于您正在为应用程序和mysql服务器使用docker容器,并且在您共享的错误中写道:

| Error: connect ECONNREFUSED 127.0.0.1:3308 

在我看来,你的docker试图连接到应用程序容器中的3308端口,而不是连接到mysql容器。

这似乎是一个docker composer配置问题。

最新更新