接口封装 wx.request
import urlConfig from './config.js'//引入接口地址,包含测试和正式地址,打包时进行切换
// method 决定是哪一种方式POST,GET.
let Server = (params, method = 'GET')=>{
let { url, data } = params; //获取传入参数
let contentType = 'application/x-www-form-urlencoded';//设置请求头
contentType = params.contentType || contentType;
wx.showLoading({
title: '努力加载中..',
mask: true
})
//promise 函数过长,声明常量替代
let promiseCopy = new Promise(function(resolve, reject) {
//wx.request 微信小程序自带的请求方式,就是对它进行的封装处理
wx.request({
url: urlConfig.HOST + url,
data: data,
method: method,
header: {
'content-type': contentType,
'Authorization': wx.getStorageSync('token')
},
success(res) {
wx.hideLoading()
if(res.data.code===401){//登录(token)过期
wx.showToast({
title: '登录过期,请重新登录',
icon:'none',
duration: 2000
})
//登录失效则跳转到登录页//针对需要登录的小程序,则需要进行此次处理
wx.navigateTo({
url: '/pages/login/index'
})
}else if(res.data.code===500||res.data.code===503){
wx.showToast({
title: res.data.message||res.data.msg||'服务异常,请稍后重试',
icon:'none',
duration: 2000
})
}else{
resolve(res.data)
}
},
fail(error) {
console.error(error)
if(error.errMsg === 'request:fail timeout'){
error.errMsg = '请求超时,请稍后重试'
}
},
error(e) {
console.log(e,'请求出错,请稍后重试...')
}
})
})
return promiseCopy
}
}
export Server