interceptors.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // 引入vuex
  2. import store from '@/common/store';
  3. const requestInterceptors=(vm)=>{
  4. /**
  5. * 请求拦截
  6. * @param {Object} http
  7. */
  8. uni.$u.http.interceptors.request.use((config) => { // 可使用async await 做异步操作
  9. // 初始化请求拦截器时,会执行此方法,此时data为undefined,赋予默认{}
  10. config.data = config.data || {}
  11. // 可以在此通过vm引用vuex中的变量,具体值在vm.$store.state中
  12. // console.log(vm.$store.state);
  13. // console.log("----------------------------------")
  14. if(config?.data?.auth) {
  15. // 获取请数据token
  16. const token = uni.getStorageSync('accessToken');
  17. // console.log("token:"+token)
  18. // 可以在此通过vm引用vuex中的变量,具体值在vm.$store.state中
  19. // config.header.token = vm.$store.state.userInfo.token
  20. if(config?.data?.requstForm){
  21. config.header = {
  22. 'Content-Type': 'application/x-www-form-urlencoded'
  23. }
  24. }
  25. config.header.Authorization = 'Bearer ' + token
  26. }
  27. // console.log("----------------------------------")
  28. return config
  29. }, (config) => // 可使用async await 做异步操作
  30. Promise.reject(config))
  31. }
  32. const responseInterceptors=(vm)=>{
  33. /**
  34. * 响应拦截
  35. * @param {Object} http
  36. */
  37. uni.$u.http.interceptors.response.use((response) => { /* 对响应成功做点什么 可使用async await 做异步操作*/
  38. const data = response.data
  39. // 自定义参数
  40. const custom = response.config?.custom
  41. if (data.code !== 200) { // 服务端返回的状态码不等于200,则reject()
  42. if (data.msg) {
  43. uni.$u.toast(data.msg)
  44. }
  45. // 如果没有显式定义custom的toast参数为false的话,默认对报错进行toast弹出提示
  46. if (custom.toast !== false) {
  47. uni.$u.toast(data.msg)
  48. }
  49. // 如果需要catch返回,则进行reject
  50. if (custom?.catch) {
  51. return Promise.reject(data)
  52. } else {
  53. // 否则返回一个pending中的promise
  54. return new Promise(() => { })
  55. }
  56. } else if(data.rows){
  57. return data;
  58. }
  59. return data.data || {}
  60. }, (response) => { /* 对响应错误做点什么 (statusCode !== 200)*/
  61. return Promise.reject(response)
  62. })
  63. }
  64. export {
  65. requestInterceptors,
  66. responseInterceptors
  67. }