带自定义头的跨域
1、index.html代码修改
// 测试getHeader方法
it("测试getHeader方法", function(done) {
//服务器返回的结果
varresult;
$.ajax({
type:"get",
url:base +"/getHeader",
headers:{
"x-header1":"AAA"
},
beforeSend: function(xhr) {
xhr.setRequestHeader("x-header2", "BBB");
},
success:function(json){
result= json;
}
});
//由于是异步请求,需要使用setTimeout来校验
setTimeout(function(){
expect(result).toEqual({
"data": "getHeader"
});
//校验完成,通知jasmine框架
done();
},100);
});
2、AjaxController.java代码
@GetMapping("/getHeader")
@ResponseBody
public ResultBean getHeader(@RequestHeader("x-header1") Stringheader1, @RequestHeader("x-header2") String header2) {
System.out.println("AjaxController.getHeader():" + header1 +" " + header2);
ResultBean resultBean = new ResultBean("getHeader");
return resultBean;
}
3、访问带自定义头的请求
4、修改CrossFilter代码
@Override
public void doFilter(ServletRequest servletRequest, ServletResponseservletResponse, FilterChain filterChain) throws IOException, ServletException{
HttpServletResponse res = (HttpServletResponse) servletResponse;
HttpServletRequest req = (HttpServletRequest) servletRequest;
String origin = req.getHeader("Origin");
//带cookie请求,origin必须全匹配
res.addHeader("Access-Control-Allow-Origin", origin);
// res.addHeader("Access-Control-Allow-Origin","http://localhost:8082");
// res.addHeader("Access-Control-Allow-Methods","GET");
// *号表示支持所有的域名(除了带cookie请求外)
// res.addHeader("Access-Control-Allow-Origin","*");
// *号表示支持所有的请求方法
res.addHeader("Access-Control-Allow-Methods", "*");
//设置允许带请求头请求
// res.addHeader("Access-Control-Allow-Headers","Content-Type,x-header1,x-//header2");
String headers =req.getHeader("Access-Control-Allow-Headers");
if (!StringUtils.isEmpty(headers)) {
res.setHeader("Access-Control-Allow-Headers", headers);
}
//设置OPTIONS预检命令缓存
res.addHeader("Access-Control-Max-Age", "60000");
//允许带cookie请求跨域
res.addHeader("Access-Control-Allow-Credentials","true");
filterChain.doFilter(servletRequest, servletResponse);
}