ajax.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import axios from 'axios';
  2. import { kuky_Authorization } from './storage';
  3. import { getConfigField } from '../config/index';
  4. /**
  5. * 处理请求路径
  6. * 当在开发模式下,使用 vite 中配置 proxy,代理所有的 /api/ 相关的请求
  7. * 开始模式下使用外网地址:http://smartai.com:8191
  8. * 使用外网地址的原因是:有其他成员在非内网环境下进行共同开发,故无法使用内网地址
  9. *
  10. * 当在production模式下,通过此处的方法,将所有 /api/ 请求地址,调整为正常的地址
  11. * @param {object} config
  12. * @returns
  13. */
  14. function applyRequestProxyUrl(config) {
  15. /**
  16. * 如果是发布模式
  17. * 则不能使用代理的方式,需要直接请求服务器路径
  18. * API_BASE_URL 需要在 /config.js 中进行配置
  19. */
  20. if (import.meta.env.MODE === 'production') {
  21. const cur_url = config.url;
  22. const is_api_request = cur_url.indexOf('/api/') === 0;
  23. if (is_api_request) {
  24. const base_url = getConfigField('API_BASE_URL');
  25. if (!base_url) {
  26. throw new Error('关键配置项 API_BASE_URL 不存在,请在 /config.js 进行配置');
  27. }
  28. const replace_str = base_url + '/';
  29. const real_url = cur_url.replace('/api/', replace_str);
  30. config.url = real_url;
  31. }
  32. } else {
  33. }
  34. return config;
  35. }
  36. const ajax = axios.create({
  37. // withCredentials: true, // 跨域发送 cookie
  38. timeout: 300000, // 请求超时
  39. headers: {
  40. 'Content-Type': 'application/json'
  41. }
  42. });
  43. ajax.interceptors.request.use(
  44. (config) => {
  45. applyRequestProxyUrl(config);
  46. const token = kuky_Authorization.get();
  47. if (token) {
  48. config.headers['Authorization'] = `Bearer ${token}`;
  49. }
  50. return config;
  51. },
  52. (error) => {
  53. // 请求出错
  54. return Promise.reject(error);
  55. }
  56. );
  57. ajax.interceptors.response.use(
  58. (response) => {
  59. const res_data = response.data;
  60. const { code, data, msg } = res_data;
  61. return res_data;
  62. },
  63. (error) => {
  64. return Promise.reject(error);
  65. }
  66. );
  67. export default ajax;