Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/hadoop/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js NodeJS用户认证中间件_Node.js_Authentication_Middleware - Fatal编程技术网

Node.js NodeJS用户认证中间件

Node.js NodeJS用户认证中间件,node.js,authentication,middleware,Node.js,Authentication,Middleware,我想为应用程序创建一个用户身份验证中间件。我不会将数据库中的任何数据用于此身份验证。假设 var user = "me"; function authme(){ //condition} 我将在路由器中使用“authme”作为中间件 app.post('/api', authme, function(res, req){ }) 我想以这样的方式编写authme函数:当user=me时,它路由这个api。我知道这是非常基本的,但我无法做到这一点。 先谢谢你 我假设您将从请求正文中的用户处收到

我想为应用程序创建一个用户身份验证中间件。我不会将数据库中的任何数据用于此身份验证。假设

var user = "me";
function authme(){
 //condition}
我将在路由器中使用“authme”作为中间件

app.post('/api', authme, function(res, req){
})
我想以这样的方式编写authme函数:当user=me时,它路由这个api。我知道这是非常基本的,但我无法做到这一点。
先谢谢你

我假设您将从请求正文中的用户处收到登录凭据

你的函数“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. 
})