TalentService-mobile/common/http.interceptor.js

81 lines
2.3 KiB
JavaScript
Raw Normal View History

2024-10-27 00:26:19 +08:00
import configService from '@/common/config.service.js';
//免登录接口
// let noLoginUrl = [
// ];
// 这里的vm就是我们在vue文件里面的this所以我们能在这里获取vuex的变量比如存放在里面的token
// 同时我们也可以在此使用getApp().globalData如果你把token放在getApp().globalData的话也是可以使用的
const install = (Vue, vm) => {
let url = ''
// 此处仅作调试新接口的开发环境,会在开发环境时影响旧接口的请求,不影响上线使用
if (process.env.NODE_ENV === 'development') {
url = configService.apiUrl;
}
// #ifdef H5
typeof window.fastUrl !== 'undefined' ? url = window.fastUrl : '',
// #endif
Vue.prototype.$u.http.setConfig({
baseUrl: url,
header: {
'content-type': 'application/json; charset=utf-8'
},
originalData: true
});
// 请求拦截配置Token等参数
Vue.prototype.$u.http.interceptor.request = (config) => {
//在需要登录的接口请求前判断token 是否存在,不存在则到登录
// if (noLoginUrl.indexOf(config.url) == -1 && !vm.vuex_token) {
// // vm.$u.route('/pages/login/mobilelogin');
// uni.navigateTo({'url':'/pages/my/compontents/login'});
// uni.showToast({'title':'请先登录', 'icon':'none'});
// return false;
// }
if (config.method == 'POST') {
config.data['__token__'] = vm.vuex__token__;
}
return config;
}
// 响应拦截,判断状态码是否通过
Vue.prototype.$u.http.interceptor.response = (res) => {
//返回__token__,设置
if (res.header.__token__) {
vm.$u.vuex('vuex__token__', res.header.__token__);
}
let result = res.data;
switch (result.code) {
case 1:
case 0:
return result;
break;
case 401:
//需要登录的接口当token 过期时,到登录页面
vm.$u.vuex('vuex_token', '');
// vm.$u.route('/pages/login/mobilelogin');
uni.navigateTo({url:'/pages/login/login'});
return result;
break;
case 403: //没有权限访问
uni.showToast({
icon: "none",
title: result.msg
})
return result;
break;
default:
if (res.statusCode == 200) {
return res.data;
} else {
console.error(res)
vm.$u.toast('网络请求错误!');
}
}
}
}
export default {
install
}