背景:
在此项目基础上,后台需要增加token进行验证,token过期自动跳转到登录界面。由于前期项目搭建未考虑这种情况,现在需要对每个接口进行重新改造。于是将uni.request进行二次封装。也方便后期使用。
- 在common/js下创建一个request.js文件
import store from '@/store/index' const request = (options) => { return new Promise((resolve,reject) => { if(options.header) { options.header['Authorization'] = 'Bearer ' + uni.getStorageSync('token') }else { let header = {'Authorization': 'Bearer ' + uni.getStorageSync('token')} options.header = header } console.log(JSON.stringify(options)); uni.request({ ...options, success: (res) => { console.log(res); if(res.data.status == '403') { // 登录过期跳转到登录界面 uni.showToast({ title: '登录超时,请重新登录!', icon: 'none' }); // logOut() } if(res.data.status == '-1') { uni.showToast({ title: res.data.msg ? res.data.msg : '接口请求失败!', icon: 'none' }); } resolve(res) }, fail: (err) => { console.log(err); console.log(options); reject(err) } }) }) } function logOut() { // let promise = this.tim.logout(); // promise.then(res=> { const userNames = uni.getStorageSync('userName'); const passwords = uni.getStorageSync('passWord'); store.commit('isLogout'); uni.clearStorage() uni.setStorageSync('userName', userNames); uni.setStorageSync('passWord', passwords); try{ const jyJPush = uni.requireNativePlugin('JY-JPush'); jyJPush.deleteJYJPushAlias( { }, result => { console.log('删除别名:' + JSON.stringify(result)); //删除别名后查看是否 jyJPush.getJYJPushAlias( { userAlias: userNames + this.config.PUSH_KEY }, result => { console.log('删除别名后查看是否还有别名存在:' + JSON.stringify(result)); } ); } ); }catch(err){ console.log(err) } uni.reLaunch({ url: '../login/login' }); // }).catch(err=> { // console.log('退出失败') // }); } export default request
2. 在main.js中挂载到全局
import request from '@/common/js/request.js'
Vue.prototype.request = request
3. 调用
this.request({ url: this.config.GET_LIST_WITH_GROUP + '?receiver=' + this.userData.id, methods: 'POST' }).then((res) => { console.log(res) // TODO },err => { uni.showToast({ title: '请求失败', icon: 'none' }); })
注意:在main.js文件挂载后,在vue文件中可以直接使用this.request调用。但是在nvue文件中,需要在该文件中重新引用后再使用。