Files
ap_trade_frontend_manage/src/api/utils.ts
2024-12-25 16:07:51 +08:00

40 lines
914 B
TypeScript

import { getToken } from "@/utils/auth";
// 创建通用请求方法
export const request = async (url: string, options: RequestInit = {}) => {
const defaultHeaders = {
"Content-Type": "application/json"
};
// 获取token
const token = getToken();
// 非登录接口才添加token
if (!url.includes("/login") && token) {
defaultHeaders["Authorization"] = `Bearer ${token}`; // 添加Bearer前缀
}
const config = {
...options,
headers: {
...defaultHeaders,
...options.headers
}
};
const response = await fetch(url, config);
const data = await response.json();
if (data.code === 200 || data.status === 200) {
return data;
} else {
throw new Error(data.message || "请求失败");
}
};
// API URL 生成器
export const authApi = (path: string) => `/auth/${path}`;
// 登录接口
export const loginApi = (path: string) => `/auth/${path}`;