带有 TypeScript 的 ExpressJs - 在中间件之间传递数据

ExpressJs with TypeScript - passing data between middlewares

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

  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错误,访问它会更容易。

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

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

declare namespace Express {
   export interface Request {
       userRole?: string // I use string for example, you can put other type
   }
}
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();
        });
    }

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