开发微信小程序时遇到一个问题,如果使用axios去进行通信的话必须替换掉axios的底层(axios本身是基于浏览器的XMLHttpRequest是实现的),如果不使用axios的话去使用uni.request又没有提供请求拦截与响应拦截,就去基于uni.request进行了二次封装了
// 项目根路径
const BaseUrl = 'https://xxxx.com/api'
const request= function(url, method, data) {
return new Promise(function (resolve, reject) {
//请求头
let header
if (wx.getStorageSync('token') !== undefined && wx.getStorageSync('token') !== "") {
header = {
'content-type': 'application/json',
'Authorization': wx.getStorageSync('token')
};
} else {
//无token情况
header = { 'content-type': 'application/json' }
}
//
uni.request({
url: BaseUrl + url,
method: method,
data: data,
header: header,
success(res) {
if (res.data.code === 200) {
resolve(res.data);
} else if (res.data.code === 10002) {
//token过期
uni.showModal({
title: '提示',
content: '身份信息失效!请重新登录!',
showCancel: false,
success(res) {
if (res.confirm) {
wx.navigateTo({
url: '/subpkg/login/login'//跳转到登录页面
})
} else if (res.cancel) {
uni.setStorageSync("token", "")
}
}
})
} else {
uni.showToast({
title: res.data.message,
icon: "none"
})
reject(res.data);
}
},
fail(err) {
uni.showToast({
title: "无法连接到服务器",
icon: "none"
})
reject(err)
}
})
})
}
- THE END -
共有 0 条评论