http.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import axios from 'axios';
  2. import { message } from 'antd';
  3. import { redirect } from 'react-router-dom';
  4. const axiosInstance = axios.create({
  5. baseURL: '/api/v1',
  6. timeout: 2000,
  7. });
  8. // 加入拦截器
  9. // 添加请求拦截器
  10. axiosInstance.interceptors.request.use(
  11. function (config) {
  12. // 在发送请求之前做些什么
  13. //! 将token信息携带上
  14. let token = sessionStorage.getItem('token');
  15. token && (config.headers['Authorization'] = token);
  16. return config;
  17. },
  18. function (error) {
  19. // 对请求错误做些什么
  20. return Promise.reject(error);
  21. }
  22. );
  23. // 添加响应拦截器
  24. axiosInstance.interceptors.response.use(
  25. function (response) {
  26. // 2xx 范围内的状态码都会触发该函数。
  27. // 对响应数据做点什么
  28. return response.data;
  29. },
  30. function (error) {
  31. // 超出 2xx 范围的状态码都会触发该函数。
  32. // 对响应错误做点什么
  33. // 401错误处理
  34. console.log(error);
  35. if (error.response.status == 401) {
  36. //! 提示用户 未登录或者 登录超时
  37. message.error('您未登录或登录已超时!请重新登录。');
  38. //! 页面重定向到 登录上
  39. redirect('/login');
  40. return Promise.resolve({});
  41. }
  42. return Promise.reject(error);
  43. }
  44. );
  45. export default axiosInstance;