ale*_*oid 23 swagger swagger-ui spring-boot swagger-2.0
我已将Swagger添加到Spring Boot 2应用程序中:
这是我的Swagger配置:
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
// @formatter:off
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
// @formatter:on
}
}
Run Code Online (Sandbox Code Playgroud)
这是Maven依赖:
<!-- Swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
当我尝试调用例如http:// localhost:8080/api/actuator/auditevents时, 它失败并出现以下错误:
TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.
Run Code Online (Sandbox Code Playgroud)
我做错了什么以及如何解决?
iro*_*ist 19
我遇到了这个问题。这是我解决它的方法:
我有一个这样的方法:
[HttpGet]
public IEnumerable<MyObject> Get(MyObject dto)
{
...
}
Run Code Online (Sandbox Code Playgroud)
我得到了错误。我相信 swagger UI 将 Get 参数解释为 FromBody,因此它使用了curl -d
标志。我添加了 [FromQuery] 装饰器,问题解决了:
[HttpGet]
public IEnumerable<MyObject> Get([FromQuery]MyObject dto)
{
...
}
Run Code Online (Sandbox Code Playgroud)
仅供参考,这也改变了该方法的 UI 体验。您将为参数对象的每个属性提供一个表单字段,而不是提供 json。
该错误消息实际上表明了问题所在。您尝试使用GET时使用-d选项使用curl发布数据。
如果使用-d选项,curl将执行POST。
如果使用-X GET选项,curl将执行GET。
该HTTP GET方法是请求指定资源的表示。使用GET的请求应仅检索数据,因此不能具有主体。
GET vs POST的更多信息
我的 .net core 2.0 解决方案和 GET 方法遇到了同样的问题,该方法将元素 ID 作为标题键或通过正文中的参数搜索它。这不是最好的实现方式,但它是一种特殊情况。
正如本次讨论中提到的。HTTP 规范不禁止在 GET 上使用 body,但 swagger 并没有像这样实现它。即使在 GET 请求中存在与 body 配合良好的 API。
更重要的是,即使它是空/未定义/空对象,swagger 前端也会将此主体对象添加到请求中。它是 -d "body_content_here" 参数。所以在我的情况下,当我只按 id 搜索并且正文为空时,它仍然发送空对象(-d "{}")并抛出提到的错误。
可能的解决方案:
开始为此请求使用邮递员应用程序 - 它将正常工作。测试。
考虑将更高级的 GET 请求(如使用条件搜索)移动到独立的 POST 方法
使用不带 -d 参数的 swagger 生成的 CURL 请求请求
小智 5
不要在 Get 方法中传递方法类型。
let res = await fetch("http://localhost:8080/employee_async",{
method: "POST",
body:JSON.stringify(data),
mode:"cors",
headers: {"Content-type":"application/json;charset=utf-8"}})
Run Code Online (Sandbox Code Playgroud)
这仅用于发布,如果我们不分配任何方法类型节点,则自动视为 Get 方法
小智 5
为了避免此错误,请务必使用 @RequestParam 注释控制器中的参数,例如
@GetMapping("/get")
public Response getData(@RequestParam String param)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
25644 次 |
最近记录: |