gpt4 book ai didi

javascript - 使用 Promise-mysql 导出 MySQL 连接以便与 Node/Express 中的其他模块一起使用?

转载 作者:行者123 更新时间:2023-11-29 06:37:31 25 4
gpt4 key购买 nike

尝试在我的 Controller 之一中导入和使用数据库模块。初始连接已被记录,但是,当我从浏览器访问任何路由时,我收到以下错误:

"Cannot read property 'query' of undefined"

database.js 文件中的连接变量显然没有被设置,但我一生都无法弄清楚为什么。


数据库.js

const mysql = require("promise-mysql");
const config = require("../config");

let connection;

mysql.createConnection(config.MYSQL)
.then(conn => {
connection = conn
console.log('Connected to ', config.MYSQL.database)
})
.catch(function (error) {
console.log(error)
})

module.exports = connection;

学校.js

const router = require('express').Router()
const Schools = require('../controllers/schools-controller')

const schools = new Schools

router.get('/', schools.getAllSchools)
...

module.exports = router

学校 Controller .js

const db = require("../lib/database");


module.exports = class Schools {

async getAllSchools (req, res, next) {

const queryString = 'SELECT * FROM schools ORDER BY school_id ASC LIMIT 5'

try {
const results = await db.query(queryString);
if (results == "") {
res.status(404).json({ message: "No schools found" });
} else {
res.status(200).json(results);
}
} catch(error) {
next(error)
}
};
...

}

下面是我根据 @Sven 的答案最终使用的池函数

数据库.js

const pool = mysql.createPool(config.MYSQL);
pool.getConnection()
.then(function(connection) {
console.log(`Connected to database: ${config.MYSQL.database}`);
pool.releaseConnection(connection)
})
.catch(function(error) {
console.error(error.message);
});

module.exports = pool;

最佳答案

您无法导出像这样异步获取的值。就像 Node 中的其他地方一样,您必须使用回调、promise 或异步函数。但是,由于这是用于 MySQL 连接,因此您应该使用 connection pool .

在您的database.js文件中:

const mysql = require("promise-mysql");
const config = require("../config");

module.exports = mysql.createPool(config.MYSQL);

您不需要对其余代码进行任何更改。

或者,您可以使用mysql2而不是 promise-mysql (基于 mysql),因为它提供了许多受欢迎的功能,listed in their readme .

您的代码只需要很少的更改,npm i -S mysql2yarn add mysql2,然后更改行 require("promise-mysql ")database.js 文件中的 require("mysql2/promise") 。可能会更新 config.js 中的配置以匹配可用于连接池的其他选项。否则,mysql2 在很大程度上与 mysql API 兼容。

关于javascript - 使用 Promise-mysql 导出 MySQL 连接以便与 Node/Express 中的其他模块一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53144644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com