gpt4 book ai didi

node.js - Express 中 Swagger API 请求的自动验证?

转载 作者:太空宇宙 更新时间:2023-11-04 00:37:07 25 4
gpt4 key购买 nike

如果这个问题看起来很明显,请原谅,但我是 Express、Node 和 Swagger 的新手。

我已经为 API 编写了 Swagger 规范。

是否有工具可以将请求与 Swagger.json 文件一起传递到 Swagger 记录的 API,以验证所需参数是否存在、这些参数的枚举值是否正确等?

类似于:

validator.validate ("./swagger.json", req, function (req, res, err) {
if (err) {
res.status('400').send(err.message());
}
else {
// Call my controller
swaggerController(req, res);
}
});

我相信有,但很难找到,或者我没有在寻找正确的东西。

最佳答案

是的,你可以做到这一点。有一个生成器项目正是可以做到这一点,无压力表达。获取 here :

使用它时,每个 API 请求都将根据您在 Api.yaml 中提供的 Swagger API 描述进行验证。

例如,要验证对 /examplesPOST 请求的 body,您可以执行以下操作:

编辑Api.yaml

...
definitions:
# define the example body i.e. require the property name
ExampleBody:
type: object
title: example
required:
- name
properties:
name:
type: string
description: The example name
paths:
# define your /examples POST endpoint
# reference the ExamplesBody definition from above
/examples:
post:
tags:
- Examples
description: Create a new example
parameters:
- name: example
in: body
description: number of items to skip
required: true
schema:
$ref: "#/definitions/ExampleBody"
responses:
200:
description: Returns all examples
...

接下来,在 Node.js 代码中为 POST 到/examples 创建一个路由处理程序

例如


app.post('/examples', function (req, res) {
/* 这里是你的处理程序逻辑 */
/* 无需验证请求负载。它会自动完成*/
});

注意:仅包含您的处理程序逻辑。正文验证将自动处理。

关于node.js - Express 中 Swagger API 请求的自动验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38531228/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com