http.interceptor.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import {
  2. config
  3. } from '@/common/config.js';
  4. import store from '@/store/index.js'
  5. let baseUrl = config.baseUrl
  6. // vm指向this
  7. const install = (Vue, vm) => {
  8. uni.$u.http.setConfig((config) => {
  9. config.baseURL = baseUrl
  10. return config
  11. });
  12. // 请求拦截,配置Token等参数
  13. uni.$u.http.interceptors.request.use((config) => {
  14. if (vm.vuex_token) {
  15. config.header.Authorization = `Bearer ${vm.vuex_token}`;
  16. }
  17. // url加时间戳
  18. config.url = config.url + '?t=' + Date.now()
  19. return config;
  20. }, config => {
  21. return Promise.reject(config)
  22. })
  23. // 响应拦截,判断状态码是否通过
  24. uni.$u.http.interceptors.response.use((response) => {
  25. let res = response.data
  26. if (res.code == 200) {
  27. return res;
  28. } else if (res.msg == "令牌不能为空" || res.code == 401) {
  29. uni.showModal({
  30. title: '提示',
  31. content: '登录信息已失效, 请重新登录',
  32. showCancel: false,
  33. success: function(res) {
  34. if (res.confirm) {
  35. uni.$u.vuex('vuex_token', '');
  36. uni.$u.vuex('vuex_user', {});
  37. uni.$u.vuex('vuex_isLogin', false);
  38. uni.redirectTo({
  39. url: "/pages/login/login"
  40. })
  41. }
  42. }
  43. });
  44. } else {
  45. uni.showToast({
  46. title: res.msg,
  47. icon: 'none',
  48. duration: 2000
  49. })
  50. }
  51. }, (response) => {
  52. return Promise.reject(response)
  53. })
  54. }
  55. export default {
  56. install
  57. }