api.js 1.2 KB

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