typescript - 带有 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”的情况下正确地将数据传递给下一个中间件?
解决方案
您可以通过创建.d.ts
文件来添加自定义快速请求类型定义
在您的根项目文件夹上创建express.d.ts
,然后放
declare namespace Express {
export interface Request {
userRole?: string // I use string for example, you can put other type
}
}
推荐阅读
- xamarin - 如何从课堂打开页面?
- vector - 试图理解向量中的手动执行
- python-3.x - 如何为 10,000 个数据框记录创建字典,然后访问每个字典记录以进行一些计算?
- android - 是否可以在 Android 中修改来电数据?
- javascript - 通过从服务器端获取数据在客户端显示字符串
- selenium - 如何将硒与灯塔集成
- node.js - 所有简单(循环)路径查询返回太多数据 -> 堆溢出
- javascript - 使用 javascript 在 for 数据循环中调用共享点 API 的最佳方法
- python-3.x - 在Python中获取一定的数字组合
- c++ - SystemKernelVaShadowInformation 和 SystemSpeculationControlInformation 是否可以替代 NtQuerySystemInformation?