跨域测试
将代码放到浏览器执行。替换自己的地址,token。
var token= "4ede4a601f674fad99e32ca5230e9c90";
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:8801/educiotlogistics/purchasing-entry/getId');
xhr.setRequestHeader("FDToken",token);
xhr.send(null);
xhr.onload = function(e) {
var xhr = e.target;
console.log(xhr.responseText);
}
出现错误
xxx has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
解决
@Bean
public CorsFilter corsConfigurer() {
// 1.添加 cors 配置
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("*");
// 是否发送cookie信息
config.setAllowCredentials(true);
// 允许的请求方式
config.addAllowedMethod("*");
// 允许的header
config.addAllowedHeader("*");
// 2.为url添加映射路径
UrlBasedCorsConfigurationSource corsSource = new UrlBasedCorsConfigurationSource();
corsSource.registerCorsConfiguration("/**", config);
return new CorsFilter(corsSource);
}