【问题标题】:Refused to apply style because its MIME type ('application/json') is not a supported stylesheet MIME type, and strict MIME checking is enabled拒绝应用样式,因为它的 MIME 类型 ('application/json') 不是受支持的样式表 MIME 类型,并且启用了严格的 MIME 检查
【发布时间】:2021-03-26 15:09:26
【问题描述】:

我将swagger-ui 添加到我的spring-boot 服务应用程序中,但在访问/swagger-ui/ 链接时出现了类似的错误。

Error in browser console please see the image(click this link)

我在招摇中的参考来自这里:

https://www.baeldung.com/swagger-2-documentation-for-spring-rest-api

这里是我的配置示例代码:

@Configuration
public class WebConfiguration implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoggerInterceptor());
    }

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

}

我尝试排除这部分:


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

仍然没有解决。希望有人可以提供帮助。谢谢。

【问题讨论】:

    标签: spring-boot swagger-ui springfox-boot-starter


    【解决方案1】:

    我正在使用 OpenApi 3,但遇到了类似的错误:

    拒绝应用来自 'http://localhost:8080/swagger-ui/swagger-ui.css' 的样式,因为它的 MIME 类型 ('application/json') 不是受支持的样式表 MIME 类型,并且有严格的 MIME 检查已启用。

    Spring Security 原来是个问题,因为没有授权,它不允许访问swagger-ui.css。以下代码解决了我的问题:

    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    // ... ommited security config
    
        @Override
        public void configure(final WebSecurity webSecurity) {
            webSecurity.ignoring().antMatchers(
                    "/v3/api-docs/**",
                    "/swagger-ui/**",
                    "/swagger-ui.html");
        }
    }
    

    您可能必须根据您的 swagger-ui URL 配置更正上述路径。此外,我建议仅将此解决方案用于 local/dev 配置文件,以免在生产环境中暴露 API 文档。 让我知道它是否解决了您的问题。如果有进一步的问题,我可以提供完整的来源。干杯。

    【讨论】:

      猜你喜欢
      • 2021-06-05
      • 2018-11-21
      • 2018-08-01
      • 2018-07-31
      • 2018-08-30
      • 2021-07-09
      • 2020-07-09
      • 2020-01-02
      • 2018-08-24
      相关资源
      最近更新 更多