swagger-ui.html頁面無法打開解決方案

最近項目集成swagger2,結果本地swagger-ui.html可以打開,但是線上環境卻無法打開。倒騰了一番終於解決問題,總結了以下幾個解決方案:

1.@EnableWebMvc註解必須去掉!

2.請實現WebMvcConfigurer,並添加如下代碼

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
  registry.addResourceHandler("swagger-ui.html")
      .addResourceLocations("classpath:/META-INF/resources/swagger-ui.html");
  registry.addResourceHandler("/webjars/**")
      .addResourceLocations("classpath:/META-INF/resources/webjars/");
}

3.檢查配置文件application.properties
  1) 將如下配置去掉,或者改成true:

spring.resources.add-mappings=false

2) 將如下配置去掉:

spring.resources.static-locations: classpath:/webapp/

4.查看nginx配置(當前項目踩坑點)

檢查前端代碼,發現nginx配置有如下一段:

location /api/swagger-ui.html{
        proxy_pass http://server-service:8080/;
        proxy_set_header X-Real-IP $remote_addr;
        client_max_body_size    1000m;
        }

由於當前應用部署在k8s環境中,後端的api地址恰好爲http://server-service:8080/,所以這個配置會導致請求直接轉發到後端接口,導致無法訪問頁面。

事實上,針對swagger,前端nginx不需要做任何映射,直接請求 http:// {後端公網host}/swagger-ui.html 即可訪問。 

參考:
https://github.com/springfox/springfox/issues/1460
https://github.com/springfox/springfox/issues/2037
https://github.com/springfox/springfox/issues/2396

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章