后端跨域设置:
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
//corsConfiguration.addAllowedOrigin("*"); 这种如果设置了setAllowCredentials(true)的话不行,会报错,报错贴在后面
// 提示需要使用下面这种形式allowedOriginPattern
corsConfiguration.addAllowedOriginPattern("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setAllowCredentials(true);
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead.
前端跨域测试
控制台输入请求后端的代码
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://127.0.0.1:18090/admin");
xhr.send({"pageNo":1,"pageSize":10});
xhr.onload = function(e) {
var xhr = e.target;
console.log(xhr.responseText);
}