【问题标题】:app.use inside a promise (bookshelf.js & express-basic-auth)承诺中的 app.use (bookshelf.js & express-basic-auth)
【发布时间】:2019-07-22 02:38:50
【问题描述】:

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/await 吗?
  • 是的,这就是我看到其他人所做的,但我已经尝试了几个小时,但我似乎无法让它发挥作用。我对 nodejs/js 很陌生。
  • 您始终可以将其余的服务器设置代码移到回调中。 apicall.then(employee => { /* tons of app.x() calls */ })

标签: javascript node.js express promise bookshelf.js


【解决方案1】:

好的,这就是我解决它的方法。

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 给我这个想法。

虽然我相信这段代码仍然可以改进,但现在,这行得通。

【讨论】:

    【解决方案2】:

    您可以使用以下结构 -

    路线 -

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

    通过这种方式,您可以添加任意数量的中间件,甚至不添加任何中间件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-22
      • 1970-01-01
      • 2015-01-29
      • 1970-01-01
      • 2018-06-23
      • 2013-06-11
      相关资源
      最近更新 更多