http.interceptor.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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头,如果有需要,则在此处设置token值
  14. // config.header.Authorization = vm.vuex_token;
  15. // 自定义全局userId参数
  16. if (vm.vuex_user.user) {
  17. config.data.userId = vm.vuex_user.user.userId;
  18. }
  19. return config;
  20. };
  21. // 响应拦截,判断状态码是否通过
  22. Vue.prototype.$u.http.interceptor.response = (res) => {
  23. // 如果把originalData设置为了true,这里得到将会是服务器返回的所有的原始数据
  24. // 判断可能变成了res.statueCode,或者res.data.code之类的,请打印查看结果
  25. if (res.code == 200) {
  26. return res;
  27. } else if (res.code == 301) {
  28. vm.$u.toast('警告:' + res.msg);
  29. return false;
  30. } else if (res.code == 401) {
  31. uni.reLaunch({
  32. url: '../login/login'
  33. })
  34. vm.$u.toast('认证失败,请重新登录')
  35. return false;
  36. } else if (res.code == 403) {
  37. uni.reLaunch({
  38. url: '../login/login'
  39. })
  40. vm.$u.toast('认证失败,请重新登录')
  41. return false;
  42. } else if (res.code == 500) {
  43. vm.$u.toast('错误:' + res.msg);
  44. return false;
  45. } else {
  46. // 其他情况都认为是不合法的
  47. vm.$u.toast('警告:' + res.msg);
  48. return false;
  49. }
  50. };
  51. }
  52. export default {
  53. install
  54. }