更新时间:2022-05-28 09:21:12
我们有一个用Express和Typescript编写的大型API,这就是我们处理此类情况的方式:
We have a large API written in Express and Typescript, and this is how we handle such scenarios:
我们将请求定义保存在一个文件中:
We keep the request definitions in one file:
import { Request } from "express"
export interface IGetUserAuthInfoRequest extends Request {
user: string // or any other type
}
然后在我们要编写控制器功能的文件中:
And then in the file where we are writing the controller functions:
import { Response } from "express"
import { IGetUserAuthInfoRequest } from "./definitionfile"
app.get('/auth/userInfo', validateUser, (req: IGetUserAuthInfoRequest, res: Response) => {
res.status(200).json(req.user); // Start calling status function to be compliant with Express 5.0
});
请注意,用户"不是Express的Request对象中本机可用的属性.确保您正在使用将此类属性添加到请求对象的中间件.
Be advised that "user" is not a property that is available natively in the Request object of Express. Make sure that you are using a middleware that adds such property to the request object.