微信小程序不能保存Cookie,導致每次wx.request到服務端都會創建一個新的會話(傳過去的sessionid會變化),小程序端就不能保持登錄狀態了。
一個比較簡單的辦法就是把服務端response的Set-Cookie中的值保存到Storage中。
登錄成功后,添加Cookie:
wx.setStorageSync("cookieKey", res.header["Set-Cookie"]);
然后調用接口時,在header中加入:
'Cookie': wx.getStorageSync('cookieKey')
接口調用由之前的:
wx.request({ url: 'test.php', data: { x: '', y: '' }, header: { 'content-type': 'application/json' }, success (res) { console.log(res.data) } }) |
變為:
wx.request({ url: 'test.php', data: { x: '', y: '' }, header: { 'content-type': 'application/json' , 'Cookie': wx.getStorageSync('cookieKey') }, success (res) { console.log(res.data) } }) |