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

元气小坏坏 提交于 2019-12-23 04:13:13

问题


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

I need my middleware (app.use) to run before my node starts so it registers. It doesn't, so when I start my node, my basic auth never registers. I'm using express-basic-auth to do the basic authentication for my api, and bookshelf.js for retrieving the values in the database.


回答1:


Okay so here is how I solved it.

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

I simply put everything that is needed before I start the server together inside my async function (below the Promise which takes time to finish).

Thanks @TommyBs and @ChrisG for giving me the idea.

Though I believe this code could still be improved, but for now, this works.




回答2:


You can use following structure -

Routes -

router.post("/home/all", [Lib.verifyToken.loginInRequired] , Controller.userChatController.homeAll);

And the Lib.verifyToken has following Method -

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


};

This way you can add as many as middleware you need or even none.



来源:https://stackoverflow.com/questions/54921318/app-use-inside-a-promise-bookshelf-js-express-basic-auth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!