前段时间对项目中的跨域做了相关的处理,网上有很多跨域的解决方案。前端解决,后端解决,nginx代理解决。我采用的是在后端中使用Cors来解决跨域的问题。但是前端项目还没有搭建起来,并不知道Cors的解决方案是否会生效,于是在今天进行了测试。

var token= "你的token"; //没有就省略
var xhr = new XMLHttpRequest();
xhr.open('GET', '请求类路径');
xhr.setRequestHeader("x-access-token",token); //没有就省略
xhr.send(null);
xhr.onload = function(e) {
var xhr = e.target;
console.log(xhr.responseText);
}
POST请求
var xhr = new XMLHttpRequest();
xhr.open('POST', '请求路径',true);
xhr.setRequestHeader('content-type', 'application/json');
var sendData = {salesmanTel:"4564564"};
//将用户输入值序列化成字符串
xhr.send(JSON.stringify(sendData));
xhr.onload = function(e) {
var xhr = e.target;
console.log(xhr.responseText);
}
public class DevopsCorsFilter {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
// 好像需要制定域
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
}

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:8081/devops/app/user/getPageQuery');
xhr.send(null);
xhr.onload = function(e) {
var xhr = e.target;
console.log(xhr.responseText);
}




如果看到这里了,说明你还是用心读完了。遇到问题不可怕,找对方案,解决问题就好了。