http.interceptor.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { config } from '@/common/config.js';
  2. import store from '@/store/index.js';
  3. // 这里的vm,就是我们在vue文件里面的this,所以我们能在这里获取vuex的变量,比如存放在里面的token
  4. // 同时,我们也可以在此使用getApp().globalData,如果你把token放在getApp().globalData的话,也是可以使用的
  5. const install = (Vue, vm) => {
  6. Vue.prototype.$u.http.setConfig({
  7. baseUrl: config.baseUrl,
  8. // 设置为json,返回后会对数据进行一次JSON.parse()
  9. dataType: 'json',
  10. showLoading: true, // 是否显示请求中的loading
  11. loadingText: '请求中...', // 请求loading中的文字提示
  12. loadingTime: 1000, // 在此时间内,请求还没回来的话,就显示加载中动画,单位ms
  13. originalData: false, // 是否在拦截器中返回服务端的原始数据
  14. loadingMask: true, // 展示loading的时候,是否给一个透明的蒙层,防止触摸穿透
  15. // 配置请求头信息
  16. header: {
  17. 'content-type': 'application/json;charset=UTF-8'
  18. }
  19. });
  20. // 请求拦截,配置Token等参数
  21. Vue.prototype.$u.http.interceptor.request = (config) => {
  22. if (vm.vuex_token) {
  23. config.header.Authorization = `Bearer ${vm.vuex_token}`;
  24. }
  25. // url加时间戳
  26. config.url = config.url + '?t=' + Date.now();
  27. let noTokenList = ['/wechat/h5/user', '/client/auth/verifyCode'];
  28. if (noTokenList.includes(config.url)) config.header.noToken = true;
  29. return config;
  30. };
  31. // 响应拦截,判断状态码是否通过
  32. Vue.prototype.$u.http.interceptor.response = (res) => {
  33. if (res.code == 200) {
  34. return res;
  35. } else if (res.msg == '令牌不能为空' || res.code == 401) {
  36. const backUrl = location.href;
  37. const loginUrl = 'phoneLogin';
  38. if (backUrl.indexOf(loginUrl) > 0) {
  39. } else {
  40. localStorage.setItem('backUrl', location.href);
  41. store.state.vuex_hasLogin = false;
  42. alert('还未登录,即将跳转登录');
  43. uni.navigateTo({
  44. url: '/pages/phoneLogin/phoneLogin'
  45. });
  46. return;
  47. }
  48. } else {
  49. uni.showToast({
  50. title: res.msg,
  51. icon: 'none',
  52. duration: 2000
  53. });
  54. }
  55. };
  56. };
  57. export default {
  58. install
  59. };