axios.js 1.3 KB

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