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

时间:2018-06-08 23:49:05

标签: mysql node.js

如何将MySQL相关功能移动到contractsService.js文件?

我收到错误:

  

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

     

ReferenceError:未定义req

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;

1 个答案:

答案 0 :(得分:1)

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