config.js
const mysql = require('mysql2');
const config = {
host: 'localhost',
port: '3306',
user: 'root',
password: 'root',
database: 'krometal',
charset: "utf8mb4_bin",
multipleStatements: true
};
const connection = mysql.createPool(config);
connection.getConnection(function (err, connection) {
//connecting to database
if (err) {
logger.log('error', err);
console.log("MYSQL CONNECT ERROR: " + err);
} else {
logger.log('info', "MYSQL CONNECTED SUCCESSFULLY.");
console.log("MYSQL CONNECTED SUCCESSFULLY.");
}
});
module.exports = {
connection
}
login.js
const loginUser = async (req, callback) => {
connection.query(sql, async function (err, rows) => {
// logic
callback(result, 401, connection);
})
}
route.js
users.post('/users/login', async (req, res) => {
await loginUser(req, async (response, code, connection) => {
await connection.end();
res.status(code).send(response);
});
});
问题是我第一次尝试登录工作正常,但如果我再次尝试相同的登录API,则抛出错误Error: Pool is closed.
我应该使用吗
connection.end((
方法每次打开连接还是mysql2自动结束连接?
不要运行
await connection.end();
运行此功能后,您需要使用创建新连接
connection.getConnection();