interceptors.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. if (response?.config?.custom?.isCloseLoad) {
  34. uni.hideLoading();
  35. }
  36. /* 对响应成功做点什么 可使用async await 做异步操作*/
  37. if(!response.data.code) response.data.code = 200;
  38. const data = response.data
  39. // console.log('http=>', data)
  40. // 自定义参数
  41. const custom = response.config?.custom
  42. if (data.code !== 200) { // 服务端返回的状态码不等于200,则reject()
  43. // 如果没有显式定义custom的toast参数为false的话,默认对报错进行toast弹出提示
  44. if (custom.toast !== false) {
  45. toast(data.msg)
  46. }
  47. if (data.code === 401) {
  48. uni.showToast({
  49. icon: 'none',
  50. title: '请先登录'
  51. })
  52. uni.redirectTo({
  53. url: '/pages/subpack/pages/login/login'
  54. })
  55. }
  56. // 如果需要catch返回,则进行reject
  57. console.log(custom);
  58. if (custom?.catch) {
  59. uni.hideLoading();
  60. return Promise.reject(data)
  61. } else {
  62. // 否则返回一个pending中的promise
  63. return new Promise(() => {})
  64. }
  65. }
  66. if (custom?.catch) {
  67. uni.hideLoading();
  68. return Promise.resolve(data)
  69. }
  70. if (!data.data && data.rows) data.data = data.rows;
  71. return data.data || {}
  72. }, (response) => {
  73. /* 对响应错误做点什么 (statusCode !== 200)*/
  74. return Promise.reject(response)
  75. })
  76. }
  77. export {
  78. requestInterceptors,
  79. responseInterceptors
  80. }