【问题标题】:how to made a middleware which can work as function if callback is provided?如果提供了回调,如何制作一个可以作为函数工作的中间件?
【发布时间】:2020-06-24 14:51:17
【问题描述】:

我想制作一个像 passport.authenticate 一样的中间件,它可以用作中间件 例如

req.get('/home', middleware,(req, res)=>{
      //some code
})

如果提供回调,它也可以作为函数工作

req.get('/home',(req,res)=>{
   auth.checkAuth((err,user)=>{
     //some code  
  })
     //some code
})

.................................................. ..................................................... auth.js 文件 这就是我正在做的-

exports.checkAuth=async(req,res,next,callback)=>{
    console.log(callback)
    const token=req.header('Authorization').replace('Bearer ',"");
    try{
        const decodedPayload= await jwt.verify(token,secretKey);
        const user=await User.findOne({_id:decodedPayload._id,'tokens.token':token});
        if(!user){
            throw Error("please! authenticate.")
        }
        req.user=user;
        req.token=token;
        res.locals.users=user;
        if(typeof(callback)=='function'?true:false){
          return  callback(null,user);
        }
        next();
    }
   catch(e){
        if(typeof(callback)=='function'?true:false){
          return  callback(e,null);
        }
        res.status(401).send(e);
    }
}

但我无法添加回调功能。

【问题讨论】:

  • auth.checkAuth((err,user)=>{...}); 无法工作,因为您从未将reqresnext 传递给它。中间件是一种非常特殊的函数类型,具有精确的调用约定。如果您使用与通常调用中间件完全相同的上下文和参数来调用该函数,则该确切函数只能在其他地方使用。
  • 是的,您可以查看一些关于该主题的教程,例如您可以在此处找到一些教程:tutorama.info/CTG/MiddleWare

标签: javascript node.js callback middleware


【解决方案1】:

中间件可以访问 req,res,next,这是由 express 完成的,它们只是一种特殊的函数,其中 req,res,next 由 express 提供。因此,如果我们想要一个可以作为中间件工作的函数,也可以作为可以传递可选回调的函数,我们必须将回调的默认值设置为 null :-

exports.checkAuth=async(req,res,next,callback=null)=>{
console.log(callback)
const token=req.header('Authorization').replace('Bearer ',"");
try{
    const decodedPayload= await jwt.verify(token,secretKey);
    const user=await User.findOne({_id:decodedPayload._id,'tokens.token':token});
    if(!user){
        throw Error("please! authenticate.")
    }
    req.user=user;
    req.token=token;
    res.locals.users=user;
    if(typeof(callback)=='function'?true:false){
      return  callback(null,user);
    }
    next();
}
 catch(e){
    if(typeof(callback)=='function'?true:false){
      return  callback(e,null);
    }
    res.status(401).send(e);
 }
}

现在将其用作中间件:-

req.get('/home',checkAuth,(req, res)=>{
  //some code
})

将其用作带有可选回调的函数:-

req.get('/home',(req,res)=>{
    auth.checkAuth((err,user)=>{
       res.send(err);  
    })
      res.send(user);
  })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-04
    • 2013-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    相关资源
    最近更新 更多