interceptors.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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.statusCode, 'proceed', res)
  8. // 只要请求成功,不管返回什么状态码,都走这个回调
  9. if (res.statusCode === HTTP_STATUS.NOT_FOUND) {
  10. Taro.setStorageSync("token", "");
  11. Taro.setStorageSync('userInfor', "");
  12. pageToLogin()
  13. // TODO 根据自身业务修改
  14. return {
  15. error: [
  16. {
  17. message: '请求资源不存在,请重新登录',
  18. start: 404
  19. }
  20. ]
  21. };
  22. } else if (res.statusCode === HTTP_STATUS.SERVER_ERROR) {
  23. return {
  24. error: [
  25. {
  26. message: '系统错误,请稍后再试',
  27. start: 500
  28. }
  29. ]
  30. }
  31. } else if (res.statusCode === HTTP_STATUS.BAD_GATEWAY) {
  32. return Promise.reject("服务端出现了问题")
  33. } else if (res.statusCode === HTTP_STATUS.FORBIDDEN || res.statusCode === HTTP_STATUS.NO_PERMISSION) {
  34. Taro.setStorageSync("token", "");
  35. Taro.setStorageSync('userInfor', "");
  36. pageToLogin()
  37. // TODO 根据自身业务修改
  38. return;
  39. } else if (res.statusCode === HTTP_STATUS.AUTHENTICATE) {
  40. Taro.setStorageSync("Authorization", "")
  41. pageToLogin()
  42. return Promise.reject("需要鉴权")
  43. } else if (res.statusCode === HTTP_STATUS.SUCCESS) {
  44. if (res.data.code === 401) {
  45. Taro.setStorageSync("token", "");
  46. Taro.setStorageSync('userInfor', "");
  47. pageToLogin()
  48. }
  49. return res.data
  50. }
  51. })
  52. }
  53. const interceptors = [customInterceptor, Taro.interceptors.logInterceptor]
  54. export default interceptors