http.interceptor.js 1.9 KB

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