aura-web/src/api/http.ts

48 lines
1.6 KiB
TypeScript

import axios from 'axios';
import { clearUserStorage } from '../utils/storage';
export const API_BASE_URL = 'https://www.tianchaoai.cc/api/v1/';
const APP_BASE = (import.meta.env.BASE_URL || '/').replace(/\/$/, '');
export const withAppBase = (path: string) => `${APP_BASE}${path.startsWith('/') ? path : `/${path}`}`;
export const withApiBase = (path: string) => `${API_BASE_URL}${path.replace(/^\//, '')}`;
export const api = axios.create({
baseURL: API_BASE_URL,
timeout: 90000,
withCredentials: true
});
// 请求拦截器
api.interceptors.request.use((config) => {
const token = localStorage.getItem('aura-token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
api.interceptors.response.use(
(r) => r,
(err) => {
const isLoginPage = location.pathname === '/login' || location.pathname === withAppBase('/login');
const isAuthPath = err.config?.url?.includes('/auth/login') || err.config?.url?.includes('/auth/register');
if (err?.response?.status === 401 && !isLoginPage && !isAuthPath) {
clearUserStorage();
let nextPath = location.pathname;
let nextSearch = location.search;
// 如果是聊天页面,只进入 /chat 列表页,不进入具体的智能体或会话,防止切换账号后的权限冲突
if (nextPath.includes('/chat')) {
nextPath = '/chat';
nextSearch = '';
}
const next = encodeURIComponent(nextPath + nextSearch);
location.href = `${withAppBase('/login')}?next=${next}`;
}
return Promise.reject(err);
}
);