微信小程序踩坑–设置cookie保持session

wx.request({
url: app.globalData.url+/user/login,           //login
data: { 
id: objData.userId,
password: objData.userPassword
},
header: { Content-Type: application/x-www-form-urlencoded },
method: POST,
success: function (res) {
    if (res && res.header && res.header[Set-Cookie]) {
         wx.setStorageSync(cookieKey, res.header[Set-Cookie]);   //保存Cookie到Storage
    }
}
})
let cookie = wx.getStorageSync(cookieKey);//取出Cookie
let header = { Content-Type: application/x-www-form-urlencoded};
if (cookie) {
     header.Cookie = cookie;
}
console.log(cookie)

然后在wx.request()中请求头直接设置成这个header就行了,需要提一嘴的是,加入Set-Cookie之前的cookie并不直接设置为空,而是

let header = { Content-Type: application/x-www-form-urlencoded};

这样能避免在POST请求中拿不到数据的情况发生。

经验分享 程序员 微信小程序 职场和发展