我想为应用程序创建用户身份验证中间件。我不会使用数据库中的任何数据进行此身份验证。假设,
var user = "me";
function authme(){
//condition}
我将在路由器中使用“authme”作为中间件。
app.post('/api', authme, function(res, req){
})
我想以某种方式编写authme函数,以便当user = me时,它会路由此api。我知道这是非常基本的,但我无法做到这一点。 先感谢您。
答案 0 :(得分:1)
我假设您将在请求正文中收到用户的登录凭据。
你的功能“authme”应该是这样的......
/*
Sample request body which you will receive from the client
{
"userId":"me",
"password":"password"
}
*/
function authme(req,res,next){
if(req.body.userId=="me" && req.body.password=="random_password"){
console.log("User authenticated");
next();
}
else{
console.log("Wrong authentication");
res.sendStatus(401);
}
}
app.post('/api', authme, function(req,res){
//the user has been authenticated.
})