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