我目前正在开发一个使用 typescript 的快速应用程序。我目前正在开发一个身份验证中间件,想知道是否可以通过某种方式使中间件类型安全:
authenticateJwt = (
req: RequestWithToken,
res: Response,
next: () => void
) => {
// Append the decoded req.token to the req header so we can use it internally
const token = req.token;
// @ts-ignore
this.verifyJwt(token)
.then((decoded: Token) => {
req.token = decoded;
next();
})
.catch(() => res.status(401).send('Unauthorized'));
};
现在在我的routes.ts中:
router.get(
'/me',
// @ts-ignore
jwtService.authenticateJwt,
userController.getProfileFromUser
);
我必须写//@ts-ignore 因为它说 '(req: RequestWithToken, res: Response, next: () => void) => void
不是 RequestHandlerParams
RequestWithToken
的定义:
export interface RequestWithToken extends Request {
token: Token;
}
export interface Token {
username: string;
}
最佳答案
创建一个custom.d.ts
并覆盖 Request
express
的界面和express-serve-static-core
declare module 'express' {
interface Request {
token: Token;
}
}
declare module 'express-serve-static-core' {
interface Request {
token: Token;
}
}
这样 RequestHandlerParams
(通常是您的 Controller )和 RequestHandler
(通常是您的中间件)正在获取新的 Request
界面。
然后将其添加到 files
您的tsconfig.json
部分:
"files": [
"src/custom.d.ts"
]
关于node.js - Typesafe Express 中间件和路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54195983/