首页 > 解决方案 > 如何从 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;

标签: mysqlnode.js

解决方案


您似乎没有将 (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

推荐阅读