访问Swagger页面无法正常显示,提示如下信息:
Unable to infer base url. This is common when using dynamic servlet registration or when the API is behind an API Gateway. The base url is the root of where all the swagger resources are served. For e.g. if the api is available at http://example.org/api/v2/api-docs then the base url is http://example.org/api/. Please enter the location manually:

基本上,这个问题和项目中全局的响应处理逻辑或者权限验证等全局性的处理逻辑有关系。
Swagger本身会提供几个后端接口供前端调用,当项目中的全局处理逻辑影响到Swagger本身的接口响应时,会导致前端解析异常进而出现这个问题。
Swagger后端接口的路径为:/swagger-resources, /swagger-resources/configuration/ui, /swagger-resources/configuration/security, /v2/api-docs, /v3/api-docs

springfox.documentation.swagger.web.ApiResourceController
springfox.documentation.swagger2.web.Swagger2Controller
springfox.documentation.oas.web.OpenApiControllerWebMvc
springfox.documentation.swagger2.web.Swagger2ControllerWebMvc

根据上述思路,逐一排查全局性的处理逻辑是否影响到swagger的接口,必要时debug一波:

  1. 项目中是否使用了 @ControllerAdvice 和 ResponseBodyAdvice?
    如果是,则需要忽略对swagger接口的处理。
  2. 项目中是否有权限验证?Swagger接口是不是被权限拦截了?
    如果是,则需要忽略对swagger接口的鉴权。
  3. 其他全局逻辑…
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐