在springboot配置中加入org.springframework.web.filter.CorsFilter过滤器,位置自定义(可以是直接的WebAppConfiguration,也可以是直接在一个能被扫描的加了org.springframework.context.annotation.Configuration注解的类中,甚至是application启动类中也行)
这里是所有资源可访问
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
return corsConfiguration;
}
/**
* 跨域过滤器
* @return
*/
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 4
return new CorsFilter(source);
}
也可以自己定义一个filter再注册到spring中,但是要注意:如果有权限控制,请让该filter优先级高于权限filter
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse httpResponse = (HttpServletResponse) res;
String [] allowDomain= {"http://132.12.11.11:8888","http://123.112.112.12:80","http://123.16.12.23","http://121.12.18.13:10195"};
Set allowedOrigins= new HashSet(Arrays.asList(allowDomain));
String originHeader=((HttpServletRequest) req).getHeader("Origin");
if (allowedOrigins.contains(originHeader)){
((HttpServletResponse) res).setHeader("Access-Control-Allow-Origin", originHeader);
((HttpServletResponse) res).setContentType("application/json;charset=UTF-8");
((HttpServletResponse) res).setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
((HttpServletResponse) res).setHeader("Access-Control-Max-Age", "3600");
((HttpServletResponse) res).setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");//表明服务器支持的所有头信息字段
((HttpServletResponse) res).setHeader("Access-Control-Allow-Credentials", "true"); //如果要把Cookie发到服务器,需要指定Access-Control-Allow-Credentials字段为true;
((HttpServletResponse) res).setHeader("XDomainRequestAllowed","1");
}
chain.doFilter(req, res);
return;
}
前端js中,这里使用原声js来做的(本人不怎么会jsonp)
var url = 'http://localhost:8080/list';
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader('X-Custom-Header', 'value');
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200){
var josnText = xhr.responseText;
var data = eval("("+josnText+")");
...
}else{
alert("有点问题哦");
}
}
}
它的过程是判断是否跨域访问,如果是的话,先使用options方法连接服务器,如果返回的origin没有当前域的话则拒绝访问。如果有(*表示对所有域开放),则再次真正访问。但整个过程于客户是没有影响的。
希望对大家有帮助,如果想深入了解Cors(Cross-Origin Resources Sharing)的同学
请入http://www.ruanyifeng.com/blog/2016/04/cors.html