axios.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { Message } from 'element-ui'
  2. export default ({ $axios, store, $cookies, redirect }) => {
  3. $axios.onRequest(config => {
  4. if (!/^\/c-api/.test(config.url)) {
  5. if (!/^\/api/.test(config.url)) {
  6. config.url = (/^\//.test(config.url) ? '/api' : '/api/') + config.url
  7. }
  8. }
  9. // const token = $cookies.get('shop-token')
  10. // if (token) {
  11. // config.headers.Authorization = 'Bearer ' + token
  12. // }
  13. })
  14. $axios.onResponse(
  15. response => {
  16. const { data, status } = response
  17. if (data.code != 1 && data.msg != 'Error' && data.msg) {
  18. Message({
  19. message: data.msg,
  20. type: 'error',
  21. duration: 3 * 1000,
  22. })
  23. return Promise.reject(new Error(data.msg || 'Error'))
  24. } else {
  25. return response.data
  26. }
  27. },
  28. error => {
  29. const { data, status } = error.response
  30. Message({
  31. message: 'error:' + data.msg,
  32. type: 'error',
  33. duration: 5 * 1000,
  34. })
  35. return Promise.reject(error)
  36. }
  37. )
  38. $axios.onError(error => {
  39. const { data, status } = error.response || { data: { msg: 'unknow'}, status: 444 }
  40. if ([303, 304, 305].includes(status)) {
  41. store.dispatch('logout')
  42. return
  43. } else if (status == 500) {
  44. redirect('/layouts/error')
  45. }
  46. if (data.code != 200) {
  47. Message({
  48. message: '' + error.response.data.msg,
  49. type: 'error',
  50. duration: 3 * 1000,
  51. })
  52. return Promise.reject(error)
  53. }
  54. })
  55. }