Node.js Typesafe Express中间件和路由?
我目前正在开发一个使用typescript的express应用程序。我目前正在开发一种身份验证中间件,并想知道您是否可以通过以下方式使中间件类型安全:Node.js Typesafe Express中间件和路由?,node.js,typescript,express,Node.js,Typescript,Express,我目前正在开发一个使用typescript的express应用程序。我目前正在开发一种身份验证中间件,并想知道您是否可以通过以下方式使中间件类型安全: authenticateJwt = ( req: RequestWithToken, res: Response, next: () => void ) => { // Append the decoded req.token to the req header so we can use it internally co
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'));
};
现在在my 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;
}
您是否尝试过:
const token = req.token as Token;
您是否尝试过:
const token = req.token as Token;
创建一个
custom.d.ts
并覆盖express
和express service static core的请求
界面
declare module 'express' {
interface Request {
token: Token;
}
}
declare module 'express-serve-static-core' {
interface Request {
token: Token;
}
}
这样,RequestHandlerParams
(通常是您的控制器)和RequestHandler
(通常是您的中间件)都可以获得新的请求
接口
然后将其添加到tsconfig.json
的文件部分:
"files": [
"src/custom.d.ts"
]
创建一个custom.d.ts
并覆盖express
和express service static core的请求
界面
declare module 'express' {
interface Request {
token: Token;
}
}
declare module 'express-serve-static-core' {
interface Request {
token: Token;
}
}
这样,RequestHandlerParams
(通常是您的控制器)和RequestHandler
(通常是您的中间件)都可以获得新的请求
接口
然后将其添加到tsconfig.json
的文件部分:
"files": [
"src/custom.d.ts"
]
如果我使用了req:Request
,并且您编写的内容表明req.token
在typeRequest
@MichelVorwieger上不存在,那么您还需要重新键入请求接口,因为它现在在我的中间件中工作,但是express路由器仍然抱怨(req:Request,res:Response,next:()=>void)=>void
不是RequestHandlerParam类型。我还通过覆盖express serve static core
@MichelVorwieger中的请求
对象修复了它,我很高兴您解决了它。我仍然会要求你回答你自己的问题,而不仅仅是对我的回答留下评论。这也将帮助其他同事。如果我使用req:Request
和您编写的内容,那么它会说req.token
在typeRequest
@MichelVorwieger上不存在,我忘了,您还需要重新键入您的请求接口,因为它现在在我的中间件中工作,但express路由器仍然抱怨(请求:请求,回复:响应,下一步:()=>void)=>void
不是RequestHandlerParam类型。我还通过覆盖express serve static core
@MichelVorwieger中的请求
对象修复了它。我很高兴你解决了这个问题。我仍然会要求你回答你自己关于这个线程的问题,而不仅仅是对我的答案发表评论。这将帮助其他同事也