http.interceptor.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { config } from '@/common/config.js';
  2. import store from '../store/index.js'
  3. // vm,就是我们在vue文件里面的this,所以我们能在这里获取vuex的变量,比如存放在里面的token
  4. const install = (Vue, vm) => {
  5. Vue.prototype.$u.http.setConfig({
  6. baseUrl: config.baseUrl,
  7. showLoading: true, // 是否显示请求中的loading
  8. loadingText: '请求中...', // 请求loading中的文字提示
  9. loadingTime: 500, // 在此时间内,请求还没回来的话,就显示加载中动画,单位ms
  10. originalData: false, // 是否在拦截器中返回服务端的原始数据
  11. loadingMask: true // 展示loading的时候,是否给一个透明的蒙层,防止触摸穿透
  12. });
  13. // 请求拦截,配置Token等参数
  14. Vue.prototype.$u.http.interceptor.request = (config) => {
  15. if(vm.vuex_token){
  16. config.header.Authorization = `Bearer ${vm.vuex_token}`;
  17. }
  18. // 请求地址加时间戳
  19. config.url = config.url + '?t=' + Date.now()
  20. let noTokenList = ['/client/wechat/h5/code/', '/client/auth/sendSmsCodeV2', '/client/auth/verifyCodeV2'];
  21. if(noTokenList.includes(config.url)) config.header.noToken = true;
  22. return config;
  23. }
  24. // 响应拦截,判断状态码是否通过
  25. Vue.prototype.$u.http.interceptor.response = (res) => {
  26. if(res.code == 200) {
  27. return res;
  28. } else if(res.code == 401 || res.code == 400) {
  29. const backUrl = location.href
  30. // 判断浏览器
  31. const ua = window.navigator.userAgent.toLowerCase();
  32. if (ua.match(/MicroMessenger/i) == 'micromessenger') {
  33. // 微信中打开
  34. vm.$u.route('pages/wechatLogin/wechatLogin', { backUrl })
  35. } else {
  36. // 普通浏览器中打开
  37. localStorage.setItem('backUrl', backUrl)
  38. localStorage.removeItem('lifeData')
  39. uni.showModal({
  40. title: '提示',
  41. content: '未查询到登录信息或信息已失效, 请重新登录',
  42. showCancel: false,
  43. success: function(res) {
  44. if (res.confirm) {
  45. uni.navigateTo({
  46. url: "/pages/center/phoneLogin/phoneLogin"
  47. })
  48. }
  49. }
  50. });
  51. }
  52. } else {
  53. uni.showToast({
  54. title: res.msg || '程序错误!',
  55. duration: 2000,
  56. icon: 'none'
  57. })
  58. };
  59. }
  60. }
  61. export default {
  62. install
  63. }