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. let baseUrl = '/api'
  7. // vm指向this
  8. const install = (Vue, vm) => {
  9. uni.$u.http.setConfig((config) => {
  10. config.baseURL = baseUrl
  11. return config
  12. });
  13. // 请求拦截,配置Token等参数
  14. uni.$u.http.interceptors.request.use((config) => {
  15. if (vm.vuex_token) {
  16. config.header.Authorization = `Bearer ${vm.vuex_token}`;
  17. }
  18. // url加时间戳
  19. config.url = config.url + '?t=' + Date.now()
  20. return config;
  21. }, config => {
  22. return Promise.reject(config)
  23. })
  24. // 响应拦截,判断状态码是否通过
  25. uni.$u.http.interceptors.response.use((response) => {
  26. let res = response.data
  27. if (res.code == 200) {
  28. return res;
  29. } else if (res.msg == "令牌不能为空" || res.code == 401) {
  30. uni.showModal({
  31. title: '提示',
  32. content: '登录信息已失效, 请重新登录',
  33. showCancel: false,
  34. success: function(res) {
  35. if (res.confirm) {
  36. store.state.vuex_isLogin = false;
  37. uni.navigateTo({
  38. url: "/pages/login/login"
  39. })
  40. }
  41. }
  42. });
  43. return;
  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. }