调整API走代理,不直接请求
This commit is contained in:
parent
d9a8da6a84
commit
694fda88c0
@ -1,10 +1,11 @@
|
||||
import axios, { type AxiosRequestConfig, type AxiosResponse } from 'axios';
|
||||
import axios, { type AxiosRequestConfig, type AxiosResponse } from "axios";
|
||||
|
||||
/**
|
||||
* 创建默认 Axios 实例
|
||||
*/
|
||||
const axiosInstance = axios.create({
|
||||
baseURL: 'http://localhost:8080',
|
||||
//#vite.config.ts中的proxy配置;不需要修改
|
||||
baseURL: "",
|
||||
timeout: 30000,
|
||||
});
|
||||
|
||||
@ -16,14 +17,18 @@ axiosInstance.interceptors.response.use(
|
||||
const { data, config } = response;
|
||||
|
||||
// 处理 Blob 响应(Orval 默认使用 blob)
|
||||
if (config?.responseType === 'blob') {
|
||||
if (config?.responseType === "blob") {
|
||||
// 如果是 JSON 响应被当作 blob 处理,需要解析
|
||||
if (data instanceof Blob) {
|
||||
const text = await data.text();
|
||||
try {
|
||||
const jsonData = JSON.parse(text);
|
||||
// 处理标准响应格式 { code, message, data }
|
||||
if (typeof jsonData === 'object' && jsonData !== null && 'code' in jsonData) {
|
||||
if (
|
||||
typeof jsonData === "object" &&
|
||||
jsonData !== null &&
|
||||
"code" in jsonData
|
||||
) {
|
||||
if (jsonData.code === 200 || jsonData.code === 0) {
|
||||
return jsonData.data;
|
||||
}
|
||||
@ -38,7 +43,7 @@ axiosInstance.interceptors.response.use(
|
||||
}
|
||||
|
||||
// 处理标准响应格式 { code, message, data }
|
||||
if (typeof data === 'object' && data !== null && 'code' in data) {
|
||||
if (typeof data === "object" && data !== null && "code" in data) {
|
||||
if (data.code === 200 || data.code === 0) {
|
||||
// 返回 data 字段
|
||||
return data.data;
|
||||
@ -53,21 +58,21 @@ axiosInstance.interceptors.response.use(
|
||||
|
||||
switch (status) {
|
||||
case 401:
|
||||
localStorage.removeItem('token');
|
||||
localStorage.removeItem('user');
|
||||
window.location.href = '/login';
|
||||
localStorage.removeItem("token");
|
||||
localStorage.removeItem("user");
|
||||
window.location.href = "/login";
|
||||
break;
|
||||
case 403:
|
||||
console.error('没有权限访问该资源');
|
||||
console.error("没有权限访问该资源");
|
||||
break;
|
||||
case 404:
|
||||
console.error('请求的资源不存在');
|
||||
console.error("请求的资源不存在");
|
||||
break;
|
||||
case 500:
|
||||
console.error('服务器内部错误');
|
||||
console.error("服务器内部错误");
|
||||
break;
|
||||
default:
|
||||
console.error('请求失败:', message);
|
||||
console.error("请求失败:", message);
|
||||
}
|
||||
|
||||
return Promise.reject(error);
|
||||
@ -86,7 +91,7 @@ export const customMutator = async <T = any>(
|
||||
options: AxiosRequestConfig,
|
||||
): Promise<AxiosResponse<T>> => {
|
||||
// 自动添加 JWT Token
|
||||
const token = localStorage.getItem('token');
|
||||
const token = localStorage.getItem("token");
|
||||
if (token) {
|
||||
options.headers = {
|
||||
...options.headers,
|
||||
|
||||
Loading…
Reference in New Issue
Block a user