首页 > 解决方案 > Springdoc:打开 swagger-ui.html 时得到 404

问题描述

我得到了最新的 Spring Boot 应用程序和 springdoc.swagger-ui。

<dependency>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-annotations</artifactId>
    <version>1.6.1</version>
</dependency>
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-ui</artifactId>
    <version>1.2.32</version>
</dependency>

我的 application.properties 包含 springdoc.swagger-ui.path=/swagger-ui-openapi.html

当我通过 Intellij IDEA 运行应用程序时,http://localhost:8080/swagger-ui-openapi.html将我带到http://localhost:8080/swagger-ui/index.html?configUrl=/v3/api-docs/ swagger-config 和 Swagger UI 页面加载成功。

但是,如果我通过命令行启动应用程序:“java -jar my-app.jar”,当我尝试访问http://localhost:8080/时,我在浏览器中得到 404,并且在日志中出现错误 'Circular view path [error]' swagger-ui-openapi.html 并将我重定向到http://localhost:8080/swagger-ui/index.html?configUrl=/v3/api-docs/swagger-config

javax.servlet.ServletException: Circular view path [error]: would dispatch back to the current handler URL [/error] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)

但是http://localhost:8080/v3/api-docs是可访问的,并且架构在此地址可用。

我怎样才能解决这个问题?

标签: spring-bootswagger-uispringdocspringdoc-openapi-ui

解决方案


当您的应用程序在代理、负载均衡器或云中运行时,在我的情况下什么是有效的。

在您的 Spring Boot 应用程序中,确保您的应用程序处理此标头:X-Forwarded-For。

有两种方法可以实现这一点:

在您的属性文件中添加:

server.use-forward-headers=true

如果这还不够,Spring Framework 提供了一个 ForwardedHeaderFilter。您可以通过将 server.forward-headers-strategy 设置为 FRAMEWORK 将其注册为应用程序中的 Servlet 过滤器。

从 Spring Boot 2.2 开始,这是处理反向代理标头的新属性:

在您的属性文件中添加

server.forward-headers-strategy=framework

您可以将以下 bean 添加到您的应用程序中:

@Bean
ForwardedHeaderFilter forwardedHeaderFilter() {
   return new ForwardedHeaderFilter();
}

如果您的根目录上已经有静态内容,并且您不希望它被 springdoc-openapi-ui 配置覆盖,您可以只定义 swagger-ui 的自定义配置,以免覆盖您的配置来自您的上下文根目录中的文件:

例如在您的属性文件中使用:

springdoc.swagger-ui.path= /swagger-ui/api-docs.html

参考: https ://springdoc.org/


推荐阅读