import axios, { type AxiosInstance, type InternalAxiosRequestConfig, } from "axios"; import { ENV } from "../config"; const request: AxiosInstance = axios.create({ baseURL: ENV.API_BASE_URL, timeout: 10000, withCredentials: false, }); // ======================= // 请求拦截器 // ======================= request.interceptors.request.use( (config: InternalAxiosRequestConfig) => { // 自动携带 token const token = localStorage.getItem("token"); if (token) { config.headers = config.headers || {}; config.headers.Authorization = `Bearer ${token}`; } return config; }, (error) => { return error; } ); // ======================= // 响应拦截器 // ======================= request.interceptors.response.use( (response) => { console.log("响应: ", response); const data = response.data; /**TODO: 增加响应码处理 */ return data; }, (error) => { /** * Promise.reject(error) 用来 返回一个状态为 rejected 的 Promise,相当于“主动抛出错误”, * * 让调用者能够在 .catch() 或 try/catch 中捕获这个错误。 它在 异步流程、拦截器、错误处理 中非常常见。 */ console.error("❌ 网络错误:", error); return Promise.reject(error); } ); export default request;