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.
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.
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