app.use inside a promise (bookshelf.js & express-basic-auth)



Api.fetchAll({columns: ['username','password']})
.then(function(employee)
{
	return employee.toJSON();
})
.then(function(employee){
	app.use(basicAuth({
			users: {employee}
		}));
});

我需要我的中间件(app.use)才能在我的节点启动之前运行,以便它注册。这不是,所以当我启动节点时,我的基本auth永远不会注册。我正在使用express-basic-auth对我的API进行基本身份验证,而书架。

好吧,这就是我解决的方式。

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();

我只是将所需的所有内容放在我的异步函数中启动服务器之前(低于承诺需要时间才能完成)。

感谢@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});
   }

};

这样,您可以添加尽可能多的中间件,甚至无需。

最新更新