interceptors.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import Taro from "@tarojs/taro"
  2. import { pageToLogin } from "./utils"
  3. import { HTTP_STATUS } from './config'
  4. const customInterceptor = (chain) => {
  5. const requestParams = chain.requestParams
  6. return chain.proceed(requestParams).then(res => {
  7. // console.log(res,'proceed')
  8. // 只要请求成功,不管返回什么状态码,都走这个回调
  9. if (res.statusCode === HTTP_STATUS.NOT_FOUND) {
  10. return {
  11. error: [
  12. {
  13. message:'请求资源不存在,请重试',
  14. start: 404
  15. }
  16. ]
  17. }
  18. } else if (res.statusCode === HTTP_STATUS.SERVER_ERROR) {
  19. return {
  20. error: [
  21. {
  22. message:'系统错误,请稍后再试',
  23. start: 500
  24. }
  25. ]
  26. }
  27. } else if (res.statusCode === HTTP_STATUS.BAD_GATEWAY) {
  28. return Promise.reject("服务端出现了问题")
  29. } else if (res.statusCode === HTTP_STATUS.FORBIDDEN || res.statusCode === HTTP_STATUS.NO_PERMISSION) {
  30. Taro.setStorageSync("token", "");
  31. Taro.setStorageSync('userInfor', "");
  32. pageToLogin()
  33. // TODO 根据自身业务修改
  34. return;
  35. } else if (res.statusCode === HTTP_STATUS.AUTHENTICATE) {
  36. Taro.setStorageSync("Authorization", "")
  37. pageToLogin()
  38. return Promise.reject("需要鉴权")
  39. } else if (res.statusCode === HTTP_STATUS.SUCCESS) {
  40. if(res.data.error && res.data.error.length !== 0 && res.data.error[0].field === '403'){
  41. Taro.setStorageSync("token", "");
  42. Taro.setStorageSync('userInfor', "");
  43. pageToLogin()
  44. }
  45. return res.data
  46. }
  47. })
  48. }
  49. const interceptors = [customInterceptor, Taro.interceptors.logInterceptor]
  50. export default interceptors