Api.fetchAll({columns: ['username','password']})
.then(function(employee)
{
return employee.toJSON();
})
.then(function(employee){
app.use(basicAuth({
users: {employee}
}));
});
我需要在我的节点启动之前运行我的中间件(app.use)才能注册。它没有,所以当我启动我的节点时,我的基本身份验证永远不会注册。我正在使用express-basic-auth为我的api执行基本身份验证,而bookshelf.js则用于检索数据库中的值。
好的,这就是我如何解决它。
async function runServerAuth (){
let employee = await Api.fetchAll({columns: ['username','password']});
employee = employee.toJSON();
app.use(basicAuth({
users: employee
}));
routes(app);
app.listen(port);
console.log('API server started on port: ' + port);
}
runServerAuth();
在我的异步函数中一起启动服务器之前,我只需要放置所需的一切(在Promise下面需要时间才能完成)。
感谢@TommyBs和@ChrisG给我的想法。
虽然我相信这段代码仍然可以改进,但就目前而言,这是可行的。
你可以使用以下结构 -
路线 -
router.post("/home/all", [Lib.verifyToken.loginInRequired] , Controller.userChatController.homeAll);
并且Lib.verifyToken具有以下方法 -
exports.loginInRequired = async function(request, response, next)
{
try{
var data = request.body;
data.userType = "User";
if (!data.accessToken)
return response.status(401).send({ success: -3, statusCode: 401, msg: response.trans("Your token has expired. Please login first")});
var userDevice = await Service.userDeviceService.userMiddlewareGet(data);
if(!userDevice)
return response.status(401).send({ success: -3, statusCode: 401, msg: response.trans("Your token has expired. Please login first")});
request.body.userDevice = userDevice;
request.body.createdAt = moment.utc().format("YYYY-MM-DD HH:mm:ss");
response.setLocale(userDevice.User.language);
next();
}
catch(e)
{
return response.status(500).json({ success: 0, statusCode: 500, msg: e.message});
}
};
这样,您可以添加所需的中间件,甚至可以添加任何中间件。