xxx has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the request resouce.前台请求出现跨域错误
关于跨域信息跨源资源共享(CORS) - HTTP | MDN (mozilla.org)
每一次跨域请求都会请求俩次第一次为预检请求第二次才是真正的请求所以在预检请求中加入允许跨域的信息即可进行跨域请求
预检请求
后台配置
@Configuration
public class MyConfig {
@Bean
public CorsWebFilter corsWebFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
//允许那些头进行跨域
corsConfiguration.addAllowedHeader("*");
//允许那些方法进行跨域
corsConfiguration.addAllowedMethod("*");
//允许哪个请求来源进行跨域
corsConfiguration.addAllowedOrigin("*");
//允许携带cookie跨域
corsConfiguration.setAllowCredentials(true);
source.registerCorsConfiguration("/**",corsConfiguration);
return new CorsWebFilter(source);
}
}