如何从 API 控制器中分解出 MySQL?



如何将MySQL相关函数移动到contractsService.js文件中?

我收到错误:

C:\code\firstdrafte2e\app.js:8 app.get('/contracts', GetContracts(req, res((; ^

引用错误:未定义 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

最新更新