swagger-ui 修改默认的请求地址

问题

将Springboot应用部署到服务器上 通过域名访问swagger-ui(经过了Nginx代理) 进行前后端联调 但是实际点击执行的时候 提示: TypeError: Failed to fetch

如 swagger-ui访问地址是:

https://foo.com/test/api/insurance/swagger-ui/index.html

点击执行 调用后端接口的地址 变成了

http://foo.com:80/solvStaInfos

因为经过Nginx代理 实际后端地址应该是

https://foo.com/test/api/insurance/solvStaInfos

解决

swagger-ui页面上地址取自接口:/v3/api-docs中的返回

servers: [
    {
        url: "http://foo.com:80",
        description: "Inferred Url"
    }
],

修改此地址为https://foo.com/test/api/insurance即可

方法一

Nginx动态修改接口返回内容

location /test/api/insurance/v3/api-docs {
    sub_filter 'http://foo.com:80' 'https://foo.com/test/api/insurance/';
    sub_filter_types application/json;
    proxy_pass ...;
}

注: 需要Nginx支持 即包含对应的module

方法二

代码层面修改

@Component
public class SpringfoxSwaggerHostResolver implements WebMvcOpenApiTransformationFilter {
    
    @Override
    public OpenAPI transform(OpenApiTransformationContext context) {
        OpenAPI swagger = context.getSpecification();
        Server server = new Server();
        server.setUrl("https://foo.com/test/api/insurance/");
        swagger.setServers(Arrays.asList(server));
        return swagger;
    }

    @Override
    public boolean supports(DocumentationType delimiter) {
        return DocumentationType.OAS_30.equals(delimiter);
    }
}

你可能感兴趣的:(nginx)