axios.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import axios from 'axios';
  2. import router from '../src/router/index';
  3. import { Message } from 'element-ui';
  4. // 添加请求拦截器
  5. axios.interceptors.request.use(function (config) {
  6. const token = sessionStorage.getItem('token');
  7. if (token) config.headers.authorization = token;
  8. return config;
  9. }, function (error) {
  10. // 对请求错误做些什么
  11. return Promise.reject(error);
  12. });
  13. // 添加响应拦截器
  14. axios.interceptors.response.use(function (response) {
  15. if (response.status == 401) {
  16. // 返回登录处理
  17. sessionStorage.removeItem('token');
  18. router.replace('/frame/login');
  19. }
  20. if (response.status == 500) {
  21. // 错误处理
  22. response.data.data = { errcode: -1001, errmsg: '服务器错误' };
  23. }
  24. return response.data;
  25. }, function (error) {
  26. Message.error('服务器错误');
  27. // 对响应错误做点什么
  28. return Promise.reject(error);
  29. });
  30. // 私有方法
  31. const request = async ({ url, method, params, data, headers }) => {
  32. return await axios.request({ url, method, params, data, headers });
  33. };
  34. // 定义类
  35. class Point {
  36. get(url, params, headers) {
  37. return request({ url, params, headers });
  38. }
  39. post(url, data, params, headers) {
  40. return request({ url, method: 'post', data, params, headers });
  41. }
  42. delete(url, params, headers) {
  43. return request({ url, method: 'delete', params, headers });
  44. }
  45. }
  46. export default new Point();