我正在我的应用程序中构建一个新端点,用作express-openapi-validator验证器中间件。
/* index.ts */
import * as OpenApiValidator from 'express-openapi-validator';
const whitelistedPaths = [/* regex tested paths */];
app.use(
OpenApiValidator.middleware({
apiSpec: './schema/api.json',
validateResponses: true,
ignorePaths: whitelistedPaths,
validateSecurity: true,
}),
);
/* ... */
app.post(
'/users/:email/validateToken',
bodyParser.json(),
(req) => validateToken(req.params.email, req.body.resetToken),
);
Run Code Online (Sandbox Code Playgroud)
在我的配置 ( api.json) 文件中,我将端点的架构定义为:
"/users/{email}/validateToken": {
"post": {
"tags": ["users"],
"summary": "Validate user token",
"operationId": "validateToken",
"responses": {
"200": {
"description": "Ok",
"content": {
"application/json": {
"schema": {}
}
}
}
},
"parameters": [
{
"name": "email",
"in": "path",
"description": "User email",
"schema": {
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"type": "object",
"required": ["resetToken"],
"properties": {
"resetToken": {
"type": "string"
}
}
}
}
}
}
}
},
Run Code Online (Sandbox Code Playgroud)
我已经使用 Postman 使用以下 JSON 主体进行了测试:
{
"resetToken": "randomd9320ru9"
}
Run Code Online (Sandbox Code Playgroud)
但收到以下错误消息:
{
"message": "request should have required property 'body'",
"errors": [
{
"path": ".body",
"message": "should have required property 'body'",
"errorCode": "required.openapi.validation"
}
]
}
Run Code Online (Sandbox Code Playgroud)
我不知道为什么它会抱怨body. 我尝试将配置放入"required": true其中requestBody,api.json但这并没有改变任何内容。我只是想确保正文包含所需的字段resetToken。
我想你需要bodyParser.json()在使用之前使用OpenApiValidator.middleware:
app.use(bodyParser.json());
app.use(
OpenApiValidator.middleware({
apiSpec: './schema/api.json',
validateRequests: true,
validateResponses: true,
ignorePaths: whitelistedPaths,
validateSecurity: true,
}),
);
...
app.post(
'/users/:email/validateToken',
(req) => validateToken(req.params.email, req.body.resetToken),
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3048 次 |
| 最近记录: |