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

问题描述 投票:0回答:4

我正在使用 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
4个回答
5
投票

您可以通过创建

.d.ts
文件来添加自定义快速请求类型定义

在根项目文件夹中创建

express.d.ts
,然后放入

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

1
投票
  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();
    });
}

请使用局部变量将值传递给下一个中间件,这样就不会显示打字稿错误,并且访问起来会更容易。


0
投票
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();
        });
    }

您可以使用它作为临时解决方案或快速修复


0
投票

我通过创建一个自定义接口来解决这个问题,该接口用我传递的数据扩展请求。然后对所有期望的请求使用这个自定义接口。

interface myRequest extends Request {
  someInfo: string
}

router.use((req: myRequest, res: Response, next) => {
  req.someInfo = 'my cool string'
})

router.get('/test', (req: myRequest, res: Response) => {
  res.send(req.someInfo)
})

这对我来说非常有用

© www.soinside.com 2019 - 2024. All rights reserved.