http.interceptor.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. let noTokenList = ['/client/auth/sendSmsCodeV2', '/client/auth/verifyCodeV2'];
  12. if(noTokenList.includes(config.url)) config.header.noToken = true;
  13. // 请求地址加时间戳
  14. config.url = config.url + '?t=' + Date.now()
  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. // 判断浏览器
  24. const ua = window.navigator.userAgent.toLowerCase();
  25. if (ua.match(/MicroMessenger/i) == 'micromessenger') {
  26. // 微信中打开
  27. vm.$u.route('pages/wechatLogin/wechatLogin', { backUrl })
  28. } else {
  29. // 普通浏览器中打开
  30. localStorage.setItem('backUrl', backUrl)
  31. localStorage.removeItem('lifeData')
  32. uni.showModal({
  33. title: '提示',
  34. content: '未查询到登录信息或信息已失效, 请重新登录',
  35. showCancel: false,
  36. success: function(res) {
  37. if (res.confirm) {
  38. uni.navigateTo({
  39. url: "/pages/center/phoneLogin/phoneLogin"
  40. })
  41. }
  42. }
  43. });
  44. }
  45. return false
  46. } else {
  47. uni.showToast({
  48. title: res.msg || '程序错误!',
  49. duration: 2000,
  50. icon: 'none'
  51. })
  52. return false
  53. };
  54. }
  55. }
  56. export default {
  57. install
  58. }