1、背景
解决微信小程序session不能使用,session 不唯一问题。
操作流程
1.调用登录请求
2.获取登录请求中的set-cookie 信息
3. 保存到本地缓存
4.每次调用加入请求头中
例如: 微信小程序调用用户信息。
login. wxml
<button bindtap="getUserInfo">getUserInfo</button>
login.js
getUserInfo(){
// 获取用户信息
httpUtils.request({
showLoading: true,
url: `/user/get/login`,
message: "正在获取用户数据..."
}).then(res => {
this.setData(
res.data.data
)
ui.showToast(res.data.errorMsg)
}).catch(err => {
console.log('ERROR')
});
},
控制台显示未登录
发现后台没有session传入
2、步骤
2.1首次请求
首次请求获取 header 中的Set-Cookie 作为cookie信息
直接开始登录流程
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
if (res.code) {
//发起网络请求
httpUtils.request({
method: "GET", showLoading: true,url: `/wx/user/wxLogin`,message: "正在登录",
data: {
code: res.code
}
}).then(res => {
if(res.header["Set-Cookie"]){
wx.setStorageSync('sessionid', res.header["Set-Cookie"]);
}
this.globalData.userInfo = res.data.data
ui.showToa