为什么ResponseHeader中没有Set-Cookie?
#使用java做微信小程序后台接口的开发。开发过小程序的都知道小程序的请求不像浏览器那样自带cookie,
这个时候session就没有办法使用,我们平时常常把用户登录信息等数据存在session中,方便后续快速取出当前请求的所属用户信息。那我们可以手动在小程序前台维护一个cookie。
当后台收到的request没有cookie时,返回的response就会有一个Set-Cookie在ResponseHeader中,前台可以把Set-Cookie取出来,保存在storage中,后续发请求就从storage取出写到hearder中。
把服务端response的Set-Cookie中的值保存到Storage中:
wx.request({
url: path,
method:method,
header: header,
data:data,
success:function(res){
if(res && res.header && res.header['Set-Cookie']){
wx.setStorageSync('cookieKey', res.header['Set-Cookie']);//保存Cookie到Storage
}
},
fail:fail
})
wx.request再从Storage中取出Cookie,封装到header中:
let cookie = wx.getStorageSync('cookieKey');
let path=conf.baseurl+url;
let header = { };
if(cookie){
header.Cookie=cookie;
}
wx.request({
url: path,
method:method,
header: header,
data:data,
success:success,
fail:fail
})
使用过程中发现,Set-Ccookie并不是每次返回请求都会有。
如果后台不创建session是不会在ResponseHearder中写Set-Cookie的。至少要有这一行:
HttpSession session = request.getSession();