const app = getApp() // 引入app
// 根据路由显示不同的加载文字
const setTitle = (url) => {
let title = '加载中'
switch (url) {
case '/user/login':
title = '登陆中'
break;
default:
break;
}
return title
}
const request = (url, options) => {
return new Promise((resolve, reject) => {
// 监听网络状态,失败则跳转网络失败页面
wx.onNetworkStatusChange(function (res) {
if(res.isConnected == false && res.networkType == "none"){
wx.navigateTo({
url: '/pages/networkanomaly/index',
})
}
})
// 加载状态文字
wx.showLoading({
title: setTitle(url),
})
wx.request({
url: `${app.globalData.baseurl}${url}`,
method: options.method,
data: options.data,
header: {
'content-type': options.isObj ? 'application/json' : 'application/x-www-form-urlencoded',
'token': wx.getStorageSync('token') || null
},
success(request) {
resolve(request)
if (request.data.code !== 200) {
wx.showToast({
title: request.data.message,
icon: 'none',
duration: 1000
})
// 300状态码为登录信息验证失效
if (request.data.code === 300) {
wx.reLaunch({
url: '/pages/login/index',
})
}
} else {
// wx.showToast({
// title: request.data.message,
// icon: 'none',
// duration: 1000
// })
}
},
fail(error) {
console.log(error, 'error');
reject(error.data)
},
complete: () => {
setTimeout(() => {
wx.hideLoading();
}, 100);
}
})
})
}
const get = (url, options = {}) => {
return request(url, {
method: 'GET',
data: options
})
}
//post对象
const postObj = (url, options) => {
return request(url, {
method: 'POST',
data: options,
isObj: true
})
}
//post参数
const post = (url, options) => {
return request(url, {
method: 'POST',
data: options,
isObj: false
})
}
const put = (url, options) => {
return request(url, {
method: 'PUT',
data: options
})
}
const remove = (url, options) => {
return request(url, {
method: 'DELETE',
data: options
})
}
module.exports = {
get,
post,
put,
remove,
postObj,
}
小程序request对象封装案例
最新推荐文章于 2022-09-18 09:52:24 发布