【问题标题】:ExpressJs with TypeScript - passing data between middlewares带有 TypeScript 的 ExpressJs - 在中间件之间传递数据
【发布时间】:2020-08-29 09:09:06
【问题描述】:

我正在使用 TypeScript 编写我的第一个 expressJs 应用程序。我得到了用于令牌验证的静态中间件方法,我需要将数据传递给下一个中间件:

    static verifyAccessToken(req: Request, resp: Response, next: NextFunction) {
        const AUTH_TOKEN = AccessTokenValidator.getTokenFromHeader(req, resp);

        jwt.verify(AUTH_TOKEN, Config.JWT_SECRET, async (error: VerifyErrors | null, payload: any) => {
            if (error) {
                resp.status(401).send({message: "Token is invalid"});
            }
            // @ts-ignore
            req.userRole = payload.rol;
            next();
        });
    }

如何在不使用“@ts-ignore”的情况下正确地将数据传递给下一个中间件?

【问题讨论】:

    标签: typescript express middleware


    【解决方案1】:

    您可以通过创建.d.ts 文件来添加自定义快速请求类型定义

    在你的根项目文件夹中创建express.d.ts,然后放入

    declare namespace Express {
       export interface Request {
           userRole?: string // I use string for example, you can put other type
       }
    }
    

    【讨论】:

      【解决方案2】:
      class CustomResponse extends Response{
          public token?:string;
      }
      

      然后继续...

      static verifyAccessToken(req:Request , resp: CustomResponse, next: NextFunction) {
              const AUTH_TOKEN = AccessTokenValidator.getTokenFromHeader(req, resp);
      
              jwt.verify(AUTH_TOKEN, Config.JWT_SECRET, async (error: VerifyErrors | null, payload: any) => {
                  if (error) {
                      resp.status(401).send({message: "Token is invalid"});
                  }
                  // @ts-ignore
                  req.userRole = payload.rol;
                  next();
              });
          }
      

      您可以将其用作临时解决方案或快速修复

      【讨论】:

        【解决方案3】:
          static verifyAccessToken(req: Request, resp: Response, next: NextFunction) {
            const AUTH_TOKEN = AccessTokenValidator.getTokenFromHeader(req, resp);
        
            jwt.verify(AUTH_TOKEN, Config.JWT_SECRET, async (error: VerifyErrors | null, payload: any) => {
                if (error) {
                    resp.status(401).send({message: "Token is invalid"});
                }
                // @ts-ignore
                resp.locals.userRole = payload.rol;
                next();
            });
        }
        

        请使用 locals 传递值到下一个中​​间件,它不会显示 typescript 错误,并且更容易访问它。

        【讨论】:

          猜你喜欢
          • 2019-02-18
          • 2021-04-02
          • 1970-01-01
          • 1970-01-01
          • 2019-01-06
          • 1970-01-01
          • 2018-12-11
          • 2017-08-26
          • 2014-02-23
          相关资源
          最近更新 更多