http.interceptor.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. store.state.vuex_isLogin = false;
  36. uni.navigateTo({
  37. url: "/pages/login/login"
  38. })
  39. }
  40. }
  41. });
  42. return;
  43. } else {
  44. uni.showToast({
  45. title: res.msg,
  46. icon: 'none',
  47. duration: 2000
  48. })
  49. }
  50. }, (response) => {
  51. return Promise.reject(response)
  52. })
  53. }
  54. export default {
  55. install
  56. }