interceptors.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import {
  2. http,
  3. toast
  4. } from '@/uni_modules/uview-plus'
  5. import store from '@/store'
  6. const requestInterceptors = (vm) => {
  7. /**
  8. * 请求拦截
  9. * @param {Object} http
  10. */
  11. http.interceptors.request.use((config) => { // 可使用async await 做异步操作
  12. // 初始化请求拦截器时,会执行此方法,此时data为undefined,赋予默认{}
  13. config.data = config.data || {}
  14. // console.log(store.state);
  15. // console.log('config', config)
  16. // config.header.token = store.state.vuex_token
  17. config.header.Authorization = 'Bearer ' + store.state.vuex_token
  18. if (config?.custom?.loading) {
  19. uni.showLoading({
  20. title: '数据加载中...'
  21. });
  22. }
  23. return config
  24. }, (config) => // 可使用async await 做异步操作
  25. Promise.reject(config))
  26. }
  27. const responseInterceptors = (vm) => {
  28. /**
  29. * 响应拦截
  30. * @param {Object} http
  31. */
  32. http.interceptors.response.use((response) => {
  33. // console.log('response: ', response);
  34. if (response?.config?.custom?.isCloseLoad) {
  35. uni.hideLoading();
  36. }
  37. /* 对响应成功做点什么 可使用async await 做异步操作*/
  38. if(!response.data.code) response.data.code = 200;
  39. const data = response.data
  40. // console.log('http=>', data)
  41. // 自定义参数
  42. const custom = response.config?.custom
  43. if (data.code !== 200) { // 服务端返回的状态码不等于200,则reject()
  44. // 如果没有显式定义custom的toast参数为false的话,默认对报错进行toast弹出提示
  45. if (custom.toast !== false) {
  46. toast(data.msg)
  47. }
  48. if (data.code === 401) {
  49. uni.showToast({
  50. icon: 'none',
  51. title: '请先登录'
  52. })
  53. uni.redirectTo({
  54. url: '/pages/subpack/pages/login/login'
  55. })
  56. }
  57. // 如果需要catch返回,则进行reject
  58. console.log(custom);
  59. if (custom?.catch) {
  60. uni.hideLoading();
  61. return Promise.reject(data)
  62. } else {
  63. // 否则返回一个pending中的promise
  64. return new Promise(() => {})
  65. }
  66. }
  67. if (custom?.catch) {
  68. uni.hideLoading();
  69. return Promise.resolve(data)
  70. }
  71. if (!data.data && data.rows) data.data = data.rows;
  72. return data.data || {}
  73. }, (response) => {
  74. /* 对响应错误做点什么 (statusCode !== 200)*/
  75. return Promise.reject(response)
  76. })
  77. }
  78. export {
  79. requestInterceptors,
  80. responseInterceptors
  81. }