import axios from 'axios'; import * as Storage from './storage'; import { notification } from 'ant-design-vue'; // const getBaseUrl = () => window.AppGlobalConfig.server; const getBaseUrl = () => '/llm'; // 请求超时时间 60s axios.defaults.timeout = 60 * 1000; const request = axios.create({ // API 请求的默认前缀 baseURL: getBaseUrl(), }); // 请求拦截器 axios.interceptors.request.use( config => { // 每次发送请求之前判断是否存在token,如果存在,则统一在http请求的header都加上token,不用每次请求都手动添加了 // 即使本地存在token,也有可能token是过期的,所以在响应拦截器中要对返回状态进行判断 const token = Storage.getCache('Token'); if (token) { config.headers.Authorization = token; } if(config.method.toUpperCase() === 'POST') { config.headers['Content-Type'] = 'application/json;charset=utf-8' } return config }, error => { return Promise.error(error) }) const errorHandler = (error) => { if (error.response) { const data = error.response.data; // 从 localstorage 获取 token // @ts-ignore // const token = userStore().accessToken; if (error.response.status === 403) { notification.error({ message: 'Forbidden', description: data.message, }); } if (error.response.status === 401 && !(data.result && data.result.isLogin)) { notification.error({ message: 'Unauthorized', description: 'Authorization verification failed', }); // if (token) { // userStore() // .loginOut() // .then(() => { // setTimeout(() => { // window.location.reload(); // }, 1500); // }); // } } if (error.code === 'ERR_NETWORK') { notification.error({ message: '网络问题', description: error.message, }); } } return Promise.reject(error); }; request.interceptors.response.use(response => { if (response?.data?.code === 401) { notification.error({ message: '用户验证失败', description: '用户信息失效,请重新登录', }); // @ts-ignore // const token = userStore().accessToken; // if (token) { // userStore() // .loginOut() // .then(() => { // setTimeout(() => { // window.location.reload(); // }, 1500); // }); // } } return response.data; }, errorHandler); export default request;