带cookie的跨域1
1、Access-Control-Allow-Origin:*解决不了带Cookie的跨域问题
在响应头中设置此字段不能满足所有解决跨域问题的场景
比如:带cookie的跨域请求
2、前端请求代码
//测试getCookie方法
it("测试getCookie方法", function(done) {
//服务器返回的结果
varresult;
$.ajax({
type:"get",
url:base +"/getCookie",
xhrFields:{
withCredentials:true
},
success:function(json){
result= json;
}
});
//由于是异步请求,需要使用setTimeout来校验
setTimeout(function(){
expect(result).toEqual({
"data": "getCookie"
});
//校验完成,通知jasmine框架
done();
},100);
});
3、cookie后端服务代码
@GetMapping("/getCookie")
@ResponseBody
public ResultBean getCookie(@CookieValue(value="cookie")String cookie){
System.out.println("AjaxController.getCookie()");
ResultBean resultBean = new ResultBean(cookie);
return resultBean;
}
public void doFilter(ServletRequest servletRequest, ServletResponseservletResponse, FilterChain filterChain) throws IOException, ServletException{
HttpServletResponse res = (HttpServletResponse) servletResponse;
//带cookie请求,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");
//设置OPTIONS预检命令缓存
res.addHeader("Access-Control-Max-Age", "60000");
//允许带cookie请求跨域
res.addHeader("Access-Control-Allow-Credentials", "true");
filterChain.doFilter(servletRequest, servletResponse);
}