responseInterceptors.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /**
  2. * 响应拦截
  3. * @param {Object} http
  4. */
  5. import Cache from '../cache'
  6. import { removeToken, setToken } from '../auth'
  7. module.exports = vm => {
  8. uni.$u.http.interceptors.response.use(
  9. response => {
  10. const data = response.data
  11. // 刷新token
  12. const authorization = response.headers?.authorization
  13. if (authorization) {
  14. setToken(authorization)
  15. }
  16. if (data.code !== 0) {
  17. uni.showModal({
  18. title: '提示',
  19. content: data.msg,
  20. showCancel: false
  21. })
  22. return Promise.reject(data.msg)
  23. }
  24. return data
  25. }, (error) => {
  26. // 401 登录超时 402 需要登录
  27. if (typeof error.data.status_code !== 'undefined') {
  28. if (error.data.status_code === 401 || error.data.status_code === 402) {
  29. if (!Cache.get('isLogin')) {
  30. removeToken(null)
  31. Cache.set('isLogin', 1)
  32. uni.reLaunch({
  33. url: '/pages/login'
  34. })
  35. }
  36. return Promise.resolve()
  37. }
  38. }
  39. uni.showModal({
  40. title: '提示',
  41. content: error.data.message,
  42. showCancel: false
  43. })
  44. return Promise.reject(error)
  45. })
  46. }