最近在代码开发中有个需求是前端ajax发起请求,需要java后台响应写入指定cookie到前台。服务端最后输出代码如下:1
2
3
4
5
6
7
8
9
10
11res.setCharacterEncoding("utf-8");
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Allow-Headers", "X-Requested-With");
//res.setHeader("Access-Control-Allow-Origin","*");
res.setHeader("Access-Control-Allow-Origin", res.getHeader("Origin"));
Cookie cookie = new Cookie("tokens", JWT);
cookie.setPath("/");
cookie.setMaxAge(MAX_AGE_SECONDS);
cookie.setHttpOnly(true);
//cookie.setSecure(true);
res.addCookie(cookie);
前台jQuery请求如下:1
2
3
4
5
6
7
8
9
10
11$.ajax({
type: "POST",
url: "http://192.168.0.102:9521/QbbsAPI/generateToken",
contentType:"application/json;charset=utf-8",
data: '{"userid":88888}',
xhrFields: {
withCredentials: true //用于发送请求时带上cookie
},
dataType:'json',
success: function( data ){alert('success')}
});
以上代码在实际运行中成功在respose header中写入了Set-Cookie,但浏览器始终没有把需要记录到本地cookie中去。经过资料查询,发现利用fetch.js改写前端ajax请求可以达到目的。改写过后的ajax请求代码如下:1
2
3
4
5
6
7
8
9
10
11
12fetch('http://192.168.0.102:9521/QbbsAPI/generateToken', {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Cache': 'no-cache'
},
body: JSON.stringify({userid:88888}),
credentials: 'include' //这句话很重要,允许跨域访问传输cookie
}).then(function(response){
alert("ok");
})
参考链接:
http://blog.csdn.net/wzl002/article/details/51441704
https://github.com/github/fetch/issues/349