我已经使用 Swagger API 文档配置了 Spring Boot 应用程序并配置了 Swagger UI。
我还在反向代理后面运行后端应用程序,该代理映射来自的所有请求host:port/api
to backend_host:port/
,当在本地主机上本地运行时,我映射localhost:8082/api
。在生产中应用了类似的映射。
当我从以下位置打开 Swagger UI 时localhost:8082/api/swagger-ui.html
它在标题下方显示以下几行:
[ 基本 URL: localhost:8080 ]
http://localhost:8082/api/v2/api-docs
当我调用任何休息操作时,swagger 总是尝试针对 localhost:8080 执行它,然后由于同源策略而失败。
我知道使用pathProvider
但它只影响基本 URL 的路径部分,而不影响域和端口。所以我只能用它来将基本 URL 更改为 localhost:8080/api,但我需要它更改为 localhost:8082/api。有没有办法将主机动态设置为浏览器中活动的当前主机和端口?
.pathProvider (new RelativePathProvider (servletContext) {
@Override
public String getApplicationBasePath() {
return "/api";
}
})
在我的例子中,使用 spring-boot:2.2.6 应用程序和 springdoc-openapi-ui:1.3.0 (也嵌入了 swagger UI),我通过以下方式解决了设置服务器 URL 的代理问题:
@Configuration
public class OpenApiConfig {
@Value("${server}")
private String url;
@Bean
@Profile("prod")
public OpenAPI customConfiguration() {
return new OpenAPI()
.servers(Collections
.singletonList(new Server().url(url))) //real public URL
.components(new Components())
.info(new Info().title("Dummy API Docs")
.description("Dummy REST API documentation"));
}
}
这一变化反映在合同中(https://real-domain.com/api-docs):
在 Swagger UI 中(https://real-domain.com/swagger-ui/index.html?configUrl=/api-docs/swagger-config)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)