mysql - 如何从 API 控制器中提取 MySQL?
问题描述
如何将 MySQL 相关函数移动到contractsService.js
文件中?
我收到一个错误:
C:\code\firstdrafte2e\app.js:8 app.get('/contracts', GetContracts(req, res)); ^
ReferenceError: req 未定义
合同服务.js
exports = function GetContracts(req, res) {
new Promise(function (resolve, reject) {
con.connect(function (err) {
if (err) throw err;
con.query("SELECT * FROM " + config.DATABASE + ".Contracts", function (err, result, fields) {
if (err) throw err;
//console.log(result);
resolve(result);
});
});
}).then(rows => res.send(rows));
}
应用程序.js
const express = require('express');
const app = express();
app.use(express.static('client'));
const config = require('./config')
var GetContracts = require('./contractsService');
app.get('/contracts', GetContracts());
module.exports = app;
解决方案
您似乎没有将 (req,res) 传递给您的 GetContracts 函数。您可以创建一个匿名函数,分配给一个变量并将其导出,如下所示。
合同服务.js
exports.GetContracts = function(req, res) {
new Promise(function (resolve, reject) {
con.connect(function (err) {
if (err) throw err;
con.query("SELECT * FROM " + config.DATABASE + ".Contracts", function (err, result, fields) {
if (err) throw err;
//console.log(result);
resolve(result);
});
});
}).then(rows => res.send(rows));
}
应用程序.js
const express = require('express');
const app = express();
app.use(express.static('client'));
const config = require('./config')
var GetContracts = require('./contractsService');
app.get('/contracts', GetContracts);
module.exports = app
推荐阅读
- php - 抓取外部 json 存储到数据库中
- swift4 - iOS HealthKit - 如何获得绝对最新的当前心率,例如手表心率并发症?
- go - 动态设置结构的键和值
- php - php循环运行命令
- c# - 抛出异常:Microsoft.Azure.Devices.Client.dll 中的“System.MissingMethodException”
- javascript - 为什么通知 API 不适用于 chrome for android?
- html - CSS Web Safe Font 中的字母间距错误
- spring - Spring Batch Stream 重启问题?
- nginx - 如何卸载从其源代码安装的 Nginx?
- linux-kernel - LinuxBoot 在固件阶段与 Coreboot 有何不同?