responseInterceptors.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /**
  2. * 响应拦截
  3. * @param {Object} http
  4. */
  5. module.exports = (vm) => {
  6. uni.$u.http.interceptors.response.use((response) => {
  7. /* 对响应成功做点什么 可使用async await 做异步操作*/
  8. const data = response.data
  9. // 自定义参数
  10. const custom = response.config?.custom
  11. // if (data.code !== 200) { // 服务端返回的状态码不等于200,则reject()
  12. // // 如果没有显式定义custom的toast参数为false的话,默认对报错进行toast弹出提示
  13. // if (custom.toast !== false) {
  14. // uni.$u.toast(data.message)
  15. // }
  16. // // 如果需要catch返回,则进行reject
  17. // if (custom?.catch) {
  18. // return Promise.reject(data)
  19. // } else {
  20. // // 否则返回一个pending中的promise
  21. // return new Promise(() => { })
  22. // }
  23. // }
  24. // return data.data || {}
  25. // 如果把originalData设置为了true,这里得到将会是服务器返回的所有的原始数据
  26. // 判断可能变成了res.statueCode,或者res.data.code之类的,请打印查看结果
  27. if (data.code == 401) {
  28. console.log("重新登录")
  29. uni.reLaunch({
  30. url: "/pages/login/index"
  31. })
  32. return
  33. }
  34. if (data.code == 422) {
  35. uni.$u.toast(data.message)
  36. return false
  37. }
  38. if (data.code == 400) {
  39. uni.$u.toast(data.message)
  40. return false
  41. }
  42. if (data.code == 500) {
  43. uni.$u.toast(data.message)
  44. return false
  45. }
  46. if (data.code < 300 && data.code >= 200) {
  47. // 如果把originalData设置为了true,这里return回什么,this.$u.post的then回调中就会得到什么
  48. return data;
  49. } else return false;
  50. }, (response) => {
  51. /* 对响应错误做点什么 (statusCode !== 200)*/
  52. return Promise.reject(response)
  53. })
  54. }