提问者:小点点

功能验证中间件节点


嗨,我对js和node js很陌生,我真的需要一些帮助。我在这个文件中导出了一个处理令牌的中间件


const jwt = require("jsonwebtoken");
const config = require("../config/config");

module.exports = (req, res, next) => {
  try {
    let token = req.headers.authorization.split(" ")[1];
    let decodeToken = jwt.verify(token, config.secrets.jwt);
    let id = decodeToken.id;
    let userType = decodeToken.userType;
    if (req.body.id && req.body.id !== id) {
      throw "Invalid user Id";
    } else {
      next();
    }
  } catch {
    res.status(401).json({
      error: new Error("Invalid request!"),
      message: "Unauthorized"
    });
  }
};

我想要的是将它包装成一个函数,该函数以有效载荷(用户id和用户类型)为参数,这样我就可以从任何其他文件访问用户id和用户类型。或者是否有其他方式从这里导出da用户id和用户类型,使其可见,以便我可以在控制器文件中使用它们,例如。谢谢:)


共1个答案

匿名用户

您将无法访问使用的“从任何其他文件”。因为用户是动态的,并且只根据HTTP请求(您的express中间件)的上下文进行解析。

所以您需要做的是将用户添加到请求上下文中,并扩展请求对象(请求对象就是上下文)。

module.exports = (req, res, next) => {
  try {
    let token = req.headers.authorization.split(" ")[1];
    let decodeToken = jwt.verify(token, config.secrets.jwt);
    let id = decodeToken.id;
    let userType = decodeToken.userType;
    if (req.body.id && req.body.id !== id) {
      throw "Invalid user Id";
    } else {
      req.user = decodeToken; // or any object that describe the user
      next();
    }
  } catch {
    ....
  }
};

现在,您可以访问控制器中的请求上下文,并根据需要使用用户

app.get('....', function(req, res){
   console.log(req.user);  // output { "id": XXX, userType: XXXX, ... }

   const userId = req.user.id;
   someService.someAction(userId, arg1, ....);
});