我无法从不同的js文件中的函数返回任何数据
token.js文件:
var express = require('express');
var jwt = require('jsonwebtoken');
var md5 = require('md5');
var Super = require('../models/super');
var db = new Super();
var router = express.Router();
/* GET users listing. */
router.post('/Login', function(req, res) {
var username = req.headers['username'];
var password = req.headers['password'];
var md5pass = md5(password);
var ress = db.get('app_user',"username = '"+username+"' and password = '"+md5pass+"'",null,null);
res.send(ress);
});
module.exports = router;
文件super.sj:
var db = require('../config/database');
class Super{
get(table, where, order, limit){
if(where != null && order != null && limit != null){
db.query('SELECT * FROM $1 WHERE $2 ORDER BY $3 LIMIT $4', [table, where, order, limit], (err, result) => {
if(err) throw err;
return result.rows;
});
}
}
}
module.exports = Super;
postman上的无法获取任何数据或错误响应
答案 0 :(得分:1)
这是假类反模式 - 你应该只导出一个函数。由于db.query
是异步的,因此如果您希望能够在其他地方使用其结果,则应将get
转换为Promise
:
var db = require('../config/database');
function get(table, where, order, limit){
return new Promise((resolve, reject) => {
if(where != null && order != null && limit != null){
db.query('SELECT * FROM $1 WHERE $2 ORDER BY $3 LIMIT $4', [table, where, order, limit], (err, result) => {
if(err) reject(err);
resolve(result.rows);
});
} else reject();
});
}
module.exports = get;
然后使用.then
(或await
)消费:
var express = require('express');
var jwt = require('jsonwebtoken');
var md5 = require('md5');
var get = require('../models/super');
var router = express.Router();
router.post('/Login', function(req, res) {
var username = req.headers['username'];
var password = req.headers['password'];
var md5pass = md5(password);
get('app_user',"username = '"+username+"' and password = '"+md5pass+"'",null,null)
.then(ress => res.send(ress));
});