gpt4 book ai didi

mysql - 如何从 API Controller 中分离出 MySQL?

转载 作者:行者123 更新时间:2023-11-29 10:12:18 25 4
gpt4 key购买 nike

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

我收到错误:

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

ReferenceError: req is not defined

contractsService.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));
}

app.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 函数。您可以创建一个匿名函数,分配给一个变量并将其导出,如下所示。

contractsService.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));

}

App.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

关于mysql - 如何从 API Controller 中分离出 MySQL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50769686/

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