responseInterceptors.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334
  1. /**
  2. * 响应拦截
  3. * @param {Object} http
  4. */
  5. module.exports = (vm) => {
  6. uni.$u.http.interceptors.response.use((response) => { /* 对响应成功做点什么 可使用async await 做异步操作*/
  7. const data = response.data
  8. // 自定义参数
  9. const custom = response.config?.custom
  10. if (data.code !== 200) { // 服务端返回的状态码不等于200,则reject()
  11. // 如果没有显式定义custom的toast参数为false的话,默认对报错进行toast弹出提示
  12. if (custom.toast !== false) {
  13. // uni.$u.toast(data.msg);
  14. console.log(data.msg);
  15. if (data.code === 401) {
  16. uni.$u.toast('请先登录');
  17. }
  18. if (data.code === 500) {
  19. uni.$u.toast(data.msg);
  20. }
  21. }
  22. // 如果需要catch返回,则进行reject
  23. if (custom?.catch) {
  24. return Promise.reject(data)
  25. } else {
  26. // 否则返回一个pending中的promise
  27. return data;
  28. }
  29. }
  30. return data || {};
  31. }, (response) => { /* 对响应错误做点什么 (statusCode !== 200)*/
  32. return Promise.reject(response)
  33. })
  34. }