| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- import axios from 'axios';
- import { kuky_Authorization } from './storage';
- import { getConfigField } from '../config/index';
- /**
- * 处理请求路径
- * 当在开发模式下,使用 vite 中配置 proxy,代理所有的 /api/ 相关的请求
- * 开始模式下使用外网地址:http://smartai.com:8191
- * 使用外网地址的原因是:有其他成员在非内网环境下进行共同开发,故无法使用内网地址
- *
- * 当在production模式下,通过此处的方法,将所有 /api/ 请求地址,调整为正常的地址
- * @param {object} config
- * @returns
- */
- function applyRequestProxyUrl(config) {
- /**
- * 如果是发布模式
- * 则不能使用代理的方式,需要直接请求服务器路径
- * API_BASE_URL 需要在 /config.js 中进行配置
- */
- if (import.meta.env.MODE === 'production') {
- const cur_url = config.url;
- const is_api_request = cur_url.indexOf('/api/') === 0;
- if (is_api_request) {
- const base_url = getConfigField('API_BASE_URL');
- if (!base_url) {
- throw new Error('关键配置项 API_BASE_URL 不存在,请在 /config.js 进行配置');
- }
- const replace_str = base_url + '/';
- const real_url = cur_url.replace('/api/', replace_str);
- config.url = real_url;
- }
- } else {
- }
- return config;
- }
- const ajax = axios.create({
- // withCredentials: true, // 跨域发送 cookie
- timeout: 300000, // 请求超时
- headers: {
- 'Content-Type': 'application/json'
- }
- });
- ajax.interceptors.request.use(
- (config) => {
- applyRequestProxyUrl(config);
- const token = kuky_Authorization.get();
- if (token) {
- config.headers['Authorization'] = `Bearer ${token}`;
- }
- return config;
- },
- (error) => {
- // 请求出错
- return Promise.reject(error);
- }
- );
- ajax.interceptors.response.use(
- (response) => {
- const res_data = response.data;
- const { code, data, msg } = res_data;
- return res_data;
- },
- (error) => {
- return Promise.reject(error);
- }
- );
- export default ajax;
|