api.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import axios from 'axios';
  2. import {
  3. ROOTPATH
  4. } from './httpUrl'
  5. // 创建axios实例
  6. const apiClient = axios.create({
  7. baseURL: ROOTPATH, // 设置你的API基础URL
  8. timeout: 5000, // 设置请求超时时间(单位:毫秒)
  9. });
  10. // 添加请求拦截器
  11. apiClient.interceptors.request.use(
  12. config => {
  13. //判断是否是表单提交form-data格式
  14. if (config.type === 'json') {
  15. config.headers['Content-Type'] = 'application/json'
  16. } else {
  17. config.headers['Content-Type'] = 'multipart/form-data'
  18. }
  19. // 在发送请求之前做些什么(例如:添加请求头,身份验证等)
  20. config.headers['token'] = localStorage.getItem('token');
  21. return config;
  22. },
  23. error => {
  24. // 对请求错误做些什么(例如:返回错误信息)
  25. return Promise.reject(error);
  26. }
  27. );
  28. // 添加响应拦截器
  29. apiClient.interceptors.response.use(
  30. response => {
  31. // 对响应数据做些什么(例如:处理返回的数据,提取有用的信息等)
  32. return response.data;
  33. },
  34. error => {
  35. // 对响应错误做些什么(例如:返回错误信息,重试等)
  36. return Promise.reject(error);
  37. }
  38. );
  39. export default apiClient;