拒绝应用样式,因为其 MIME 类型('application/json')不是受支持的样式表 MIME 类型,并且启用了严格的 MIME 检查

Dan*_*iel 4 swagger-ui spring-boot springfox-boot-starter

我添加swagger-ui到我的 spring-boot 服务应用程序中,在访问链接时遇到了一些类似的错误/swagger-ui/

浏览器控制台出错,请查看图片(点击此链接)

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

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/");
    }

}
Run Code Online (Sandbox Code Playgroud)

我尝试排除这部分:


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

仍然没有决心。希望有人可以帮忙。谢谢。

Luk*_*iak 8

我正在使用 OpenApi 3 并且遇到类似的错误:

拒绝应用“http://localhost:8080/swagger-ui/swagger-ui.css”中的样式,因为其 MIME 类型(“application/json”)不是受支持的样式表 MIME 类型,并且启用了严格的 MIME 检查。

swagger-ui.css结果Spring Security出了问题,因为没有授权而不允许访问。以下代码解决了我的问题:

@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");
    }
}
Run Code Online (Sandbox Code Playgroud)

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