http.interceptor.js 2.7 KB

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