interceptors.js 2.3 KB

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