微信小程序带cookie的request请求代码封装
2018-12-13 本文已影响0人
渔父歌
微信小程序带cookie的request请求代码封装
写一个工具函数,直接导入使用即可,接口同 wx.request
。会自动设置和更新 cookie。
const request = function (obj) {
//设置cookie缓存
if(obj.fail){
obj.fail = function(err){
wx.setStorageSync('cookie', err.header['Set-Cookie']);
obj.fail(err);
};
}
else{
obj.fail = function (err) {
wx.setStorageSync('cookie', err.header['Set-Cookie']);
};
}
if(obj.success){
obj.success = function (res) {
wx.setStorageSync('cookie', res.header['Set-Cookie']);
obj.success(res);
};
}
else{
obj.success = function (res) {
wx.setStorageSync('cookie', res.header['Set-Cookie']);
};
}
//设置请求头
if(obj.header){
obj.header = {
'Cookie': wx.getStorageSync('cookie'),
"Content-Type": "application/x-www-form-urlencoded",
...obj.header
};
}
else{
obj.header = {
'Cookie': wx.getStorageSync('cookie'),
"Content-Type": "application/x-www-form-urlencoded",
};
}
wx.request(obj);
};
module.exports = {
request: request
};