首页 > 解决方案 > 带有 TypeScript 的 ExpressJs - 在中间件之间传递数据

问题描述

我正在使用 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”的情况下正确地将数据传递给下一个中间件?

标签: typescriptexpressmiddleware

解决方案


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

在您的根项目文件夹上创建express.d.ts,然后放

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

推荐阅读