问题发生场景
注册功能, 小程序端第一次调用【发送验证码】接口, 服务器端将验证码存入 session 中。 小程序端第二次调用【注册】接口, 服务器端接收小程序请求的 sessionid, 通过 sessionid 找到 session, 并判断验证码是不是正确
问题现象
小程序端两次请求的 sessionid 不一致, 导致后端无法取得 session
解决办法
小程序第一次请求, 从服务器端返回的数据中取得 sessionid, 并存到缓存中或全局变量中
wx.request({
url: config.api_url,
data: {
userPhone: phone
},
success: (res) => {
if (res && res.header && res.header['Set-Cookie']) {
wx.setStorageSync('cookieKey', res.header['Set-Cookie']); //保存Cookie到Storage
}
}
})
小程序第二次请求时, 从缓存中读取 sessionid, 并传递给服务器端
http.request({
url: '/xxx',
header: {
'Cookie': wx.getStorageSync('cookieKey')
},
data: {
userPhone: phone
},
success: (data) => {
console.log(data)
}
})
http 为封装的工具类, 主要关注这部分代码
header: { 'Cookie': wx.getStorageSync('cookieKey') }