http.interceptor.js 2.3 KB

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