http.interceptor.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // 这里的vm,就是我们在vue文件里面的this,所以我们能在这里获取vuex的变量,比如存放在里面的token
  2. // 同时,我们也可以在此使用getApp().globalData,如果你把token放在getApp().globalData的话,也是可以使用的
  3. import config from "./config.js" // 全局配置文件
  4. const install = (Vue, vm) => {
  5. Vue.prototype.$u.http.setConfig({
  6. // baseUrl打包app时放开,h5模式下会和vue.config.js代理冲突,导致失效
  7. baseUrl: config.baseUrl,
  8. });
  9. // 请求拦截,配置Token等参数
  10. Vue.prototype.$u.http.interceptor.request = (config) => {
  11. // config.header.Token = '5d33018e653d897fc259b42cf022c1b3';
  12. // 方式一,存放在vuex的token,假设使用了uView封装的vuex方式,见:https://uviewui.com/components/globalVariable.html
  13. // 自定义token头
  14. // config.header.Authorization = vm.vuex_token;
  15. return config;
  16. };
  17. // 响应拦截,判断状态码是否通过
  18. Vue.prototype.$u.http.interceptor.response = (res) => {
  19. // 如果把originalData设置为了true,这里得到将会是服务器返回的所有的原始数据
  20. // 判断可能变成了res.statueCode,或者res.data.code之类的,请打印查看结果
  21. if (res.code == 200) {
  22. return res;
  23. } else if (res.code == 301) {
  24. vm.$u.toast('警告:' + res.msg);
  25. return false;
  26. } else if (res.code == 401) {
  27. uni.reLaunch({
  28. url: '../login/login'
  29. })
  30. vm.$u.toast('认证失败,请重新登录')
  31. return false;
  32. } else if (res.code == 403) {
  33. uni.reLaunch({
  34. url: '../login/login'
  35. })
  36. vm.$u.toast('认证失败,请重新登录')
  37. return false;
  38. } else if (res.code == 500) {
  39. vm.$u.toast('错误:' + res.msg);
  40. return false;
  41. } else {
  42. // 其他情况都认为是不合法的
  43. vm.$u.toast('警告:' + res.msg);
  44. return false;
  45. }
  46. };
  47. }
  48. export default {
  49. install
  50. }