经常会遇到要对请求的某个code做统一的处理,比如headers带Token的时候
所以自己封装了个wx.request的插件
1、使用promise封装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| const app = getApp()
function netRequest(config) { let promise = new Promise(function(resolve, reject) { wx.showNavigationBarLoading() let token = app.globalData.token ? app.globalData.token : ''; if (token) { config.header['Authorization'] = token } wx.request({ url: config.url, data: config.data, method: config.method, header: config.header, success: function (res) { if(res.statusCode == 200 && res.data.code!==401) { resolve(res.data); return } if (res.statusCode == 200 && res.data.code == 401) { wx.showToast({ title: 'token过期,请重新登录', icon: 'none', duration: 1500, mask: true }) setTimeout(()=>{ wx.navigateTo({ url: '../login/login', }) },1500) reject(res); return } }, fail: function (res) { reject(res); }, complete() { wx.hideNavigationBarLoading() } }); }); return promise; }
export default netRequest;
|
2、调用方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| import netRequest from '../../utils/netRequest.js';
...
getList(){ let url = API.domain + API.houseList; let obj = { url: url, method: "GET", header:{ }, data: { userIndexCode: app.globalData.userIndexCode, } }; netRequest(obj).then( res => { console.log(res); } }).catch( err => { wx.showToast({ title: err, icon: 'loading', duration: 1500, mask: true }) }) }
|