interceptors.js 1.9 KB

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