http.interceptor.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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,
  8. loadingText: '加载中...',
  9. loadingMask: true,
  10. loadingTime: 100
  11. });
  12. // 请求拦截,配置Token等参数
  13. Vue.prototype.$u.http.interceptor.request = (config) => {
  14. if(vm.vuex_token){
  15. config.header.Authorization = `Bearer ${vm.vuex_token}`;
  16. }
  17. // 请求地址加时间戳
  18. config.url = config.url + '?t=' + Date.now()
  19. let noTokenList = ['/client/wechat/h5/code/', '/client/auth/sendSmsCodeV2', '/client/auth/verifyCodeV2'];
  20. if(noTokenList.includes(config.url)) config.header.noToken = true;
  21. return config;
  22. }
  23. // 响应拦截,判断状态码是否通过
  24. Vue.prototype.$u.http.interceptor.response = (res) => {
  25. if(res.code == 200) {
  26. return res;
  27. } else if(res.code == 401 || res.code == 400) {
  28. const backUrl = location.href
  29. // 判断浏览器
  30. const ua = window.navigator.userAgent.toLowerCase();
  31. if (ua.match(/MicroMessenger/i) == 'micromessenger') {
  32. // 微信中打开
  33. vm.$u.route('pages/wechatLogin/wechatLogin', { backUrl })
  34. } else {
  35. // 普通浏览器中打开
  36. localStorage.setItem('backUrl', backUrl)
  37. localStorage.removeItem('lifeData')
  38. uni.showModal({
  39. title: '提示',
  40. content: '未查询到登录信息或信息已失效, 请重新登录',
  41. showCancel: false,
  42. success: function(res) {
  43. if (res.confirm) {
  44. uni.navigateTo({
  45. url: "/pages/center/phoneLogin/phoneLogin"
  46. })
  47. }
  48. }
  49. });
  50. }
  51. } else {
  52. uni.showToast({
  53. title: res.msg || '程序错误!',
  54. duration: 2000,
  55. icon: 'none'
  56. })
  57. };
  58. }
  59. }
  60. export default {
  61. install
  62. }