http.interceptor.js 2.2 KB

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