跨域问题,springboot项目It does not have HTTP ok status.

has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

定义一个配置类,实现WebMvcConfigurer接口,重写addCorsMappings方法,代码如下:


registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD")
                .maxAge(3600);

你需要配置一个跨域请求类将其交给springboot,在你的项目里面新建一个config包,里面创建一个允许跨域请求类CorsConfig实现WebMvcConfigurer,代码如下

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }

    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
//          .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                .maxAge(3600);
    }
}

然后重启项目即可解决跨域问题