我在我的项目中使用 ExpressJS 4,它遵循 MVC 架构。我创建了一个帮助程序,我可以在其中编写从数据库(DRY 方法)查询数据的常用函数,并且可以从任何控制器访问这些函数。我可以调用辅助函数并将数据传递给它,但我无法从中查询数据库。
这是我的控制器 ( dumyController.js
) 的示例:
'use strict';
var dbHelpers = require('../helpers/helpers');
exports.dummyFunction = function (req, res) {
var id=165;
var abc = dbHelpers.dummyHelperFunction(iddd);
console.log(abc);
};
如您所见,我正在控制器中调用辅助函数。这是帮助器的示例 ( helpers.js
)
var db = require('../db');
module.exports = {
dummyHelperFunction: function (passvar) {
var params = [passvar];
var query = `SELECT email FROM members where id=?`;
return db.query(query, params);
}
};
如果您想知道我的数据库连接是否有任何问题,则没有与此相关的问题。不过还是分享一下(db.js
)
var mysql = require('mysql');
var connection = mysql.createPool({
host: '127.0.0.1',
user: 'root',
password: '',
database: 'dumyDB'
});
module.exports = connection;
我正在尝试获取 MySQL 查询返回的结果,但这就是我在 console.log 时得到的结果。
Query {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
_callback: undefined,
_callSite:
Error
at Pool.query (_PROJECT-PATH_\node_modules\mysql\lib\Pool.js:199:23)
at Object.dummyHelperFunction (_PROJECT-PATH_\helpers\helpers.js:18:15)
at exports.dummyFunction (_PROJECT-PATH_\controllers\dumyController.js:227:25)
at Layer.handle [as handle_request] (_PROJECT-PATH_\node_modules\express\lib\router\layer.js:95:5)
at next (_PROJECT-PATH_\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (_PROJECT-PATH_\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (_PROJECT-PATH_\node_modules\express\lib\router\layer.js:95:5)
at _PROJECT-PATH_\node_modules\express\lib\router\index.js:281:22
at Function.process_params (sam_PROJECT-PATH_ple\node_modules\express\lib\router\index.js:335:12)
at next (_PROJECT-PATH_\node_modules\express\lib\router\index.js:275:10),
_ended: false,
_timeout: undefined,
_idleNext: null,
_idlePrev: null,
_idleStart: null,
_idleTimeout: -1,
_repeat: null,
sql: 'SELECT email FROM members where id=?',
values: [ 165 ],
typeCast: true,
nestTables: false,
_resultSet: null,
_results: [],
_fields: [],
_index: 0,
_loadError: null }