interceptors.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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)
  16. // config.header.token = store.state.vuex_token
  17. config.header.Authorization = 'Bearer ' + store.state.vuex_token
  18. return config
  19. }, (config) => // 可使用async await 做异步操作
  20. Promise.reject(config))
  21. }
  22. const responseInterceptors = (vm) => {
  23. /**
  24. * 响应拦截
  25. * @param {Object} http
  26. */
  27. http.interceptors.response.use((response) => {
  28. // console.log('response: ', response);
  29. /* 对响应成功做点什么 可使用async await 做异步操作*/
  30. const data = response.data
  31. // console.log('http', data)
  32. // 自定义参数
  33. const custom = response.config?.custom
  34. if (data.code !== 200) { // 服务端返回的状态码不等于200,则reject()
  35. // 如果没有显式定义custom的toast参数为false的话,默认对报错进行toast弹出提示
  36. if (custom.toast !== false) {
  37. toast(data.msg)
  38. }
  39. if (data.code === 401) {
  40. uni.showToast({
  41. icon: 'none',
  42. title: '请先登录'
  43. })
  44. uni.redirectTo({
  45. url: '/pages/subpack/pages/login/login'
  46. })
  47. }
  48. // 如果需要catch返回,则进行reject
  49. if (custom?.catch) {
  50. uni.hideLoading();
  51. return Promise.reject(data)
  52. } else {
  53. // 否则返回一个pending中的promise
  54. return new Promise(() => {})
  55. }
  56. }
  57. return data.data || {}
  58. }, (response) => {
  59. /* 对响应错误做点什么 (statusCode !== 200)*/
  60. return Promise.reject(response)
  61. })
  62. }
  63. export {
  64. requestInterceptors,
  65. responseInterceptors
  66. }