http.interceptor.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import {
  2. baseUrl
  3. } from "@/common/env.js"
  4. const install = (Vue, vm) => {
  5. Vue.prototype.$u.http.setConfig({
  6. baseUrl: baseUrl,
  7. showLoading: true, // 是否显示请求中的loading
  8. loadingText: '加载中', // 请求loading中的文字提示
  9. loadingTime: 800, // 在此时间内,请求还没回来的话,就显示加载中动画,单位ms
  10. loadingMask: true, // 展示loading的时候,是否给一个透明的蒙层,防止触摸穿透
  11. header: {
  12. 'content-type': 'application/x-www-form-urlencoded'
  13. },
  14. });
  15. // 请求拦截,配置Token等参数
  16. Vue.prototype.$u.http.interceptor.request = (config) => {
  17. // 引用token
  18. // 方式一,存放在vuex的token,假设使用了uView封装的vuex方式
  19. // 见:https://uviewui.com/components/globalVariable.html
  20. // config.header.token = vm.token;
  21. config.header.Token = vm.vuex_token;
  22. // 可以对某个url进行特别处理,此url参数为this.$u.get(url)中的url值
  23. // if (config.url == '/user/login') config.header.noToken = true;
  24. // 最后需要将config进行return
  25. return config;
  26. // 如果return一个false值,则会取消本次请求
  27. // if(config.url == '/user/rest') return false; // 取消某次请求
  28. }
  29. // 响应拦截,判断状态码是否通过
  30. Vue.prototype.$u.http.interceptor.response = (res) => {
  31. if (res.code == 200) {
  32. // res为服务端返回值,可能有code,result等字段
  33. // 这里对res.result进行返回,将会在this.$u.post(url).then(res => {})的then回调中的res的到
  34. // 如果配置了originalData为true,请留意这里的返回值
  35. return res;
  36. } else if (res.code == 603||res.code == 403) {
  37. // // 假设201为token失效,这里跳转登录
  38. vm.$u.toast('验证失败,请重新登录', 1000);
  39. setTimeout(() => {
  40. // 此为uView的方法,详见路由相关文档
  41. vm.$u.route('/pages/login/login')
  42. }, 1500)
  43. return false;
  44. } else {
  45. // 如果返回false,则会调用Promise的reject回调,
  46. // 并将进入this.$u.post(url).then().catch(res=>{})的catch回调中,res为服务端的返回值
  47. vm.$u.toast(res.message, 1500);
  48. return false;
  49. }
  50. }
  51. }
  52. export default {
  53. install
  54. }