http.interceptor.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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: 100
  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. vm.$u.route('pages/wechatLogin/wechatLogin', { backUrl })
  32. } else {
  33. // 普通浏览器中打开
  34. localStorage.setItem('backUrl', backUrl)
  35. localStorage.removeItem('lifeData')
  36. uni.showModal({
  37. title: '提示',
  38. content: '未查询到登录信息或信息已失效, 请重新登录',
  39. showCancel: false,
  40. success: function(res) {
  41. if (res.confirm) {
  42. uni.redirectTo({
  43. url: "/pages/center/phoneLogin/phoneLogin"
  44. })
  45. }
  46. }
  47. });
  48. }
  49. return false
  50. } else {
  51. uni.showToast({
  52. title: res.msg || '程序错误!',
  53. duration: 2000,
  54. icon: 'none'
  55. })
  56. return false
  57. };
  58. }
  59. }
  60. export default {
  61. install
  62. }