http.interceptor.js 1.8 KB

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