This commit is contained in:
2025-10-21 18:50:12 +08:00
parent 2ab8b06c6a
commit 476944d22e
3 changed files with 73 additions and 30 deletions

View File

@@ -1,10 +1,8 @@
import type { Project, UploadResponse, ToggleResponse } from '../types'
import type { Project, UploadResponse, ToggleResponse } from "../types"
// 动态获取API基础URL
const getApiBase = () => {
// 在Docker环境中前端通过Caddy代理访问后端
if (window.location.hostname !== 'localhost') {
return '/api'
return `${window.location.protocol}//${window.location.host}/api`
}
// 开发环境直接访问后端
return 'http://localhost:3000/api'
@@ -15,7 +13,7 @@ async function request<T>(url: string, options: RequestInit = {}): Promise<T> {
const API_BASE = getApiBase()
const response = await fetch(`${API_BASE}${url}`, {
headers: {
'Content-Type': 'application/json',
"Content-Type": "application/json",
...options.headers,
},
...options,
@@ -24,7 +22,7 @@ async function request<T>(url: string, options: RequestInit = {}): Promise<T> {
const data = await response.json()
if (!response.ok) {
throw new Error(data.error || '请求失败')
throw new Error(data.error || "请求失败")
}
return data
@@ -33,25 +31,32 @@ async function request<T>(url: string, options: RequestInit = {}): Promise<T> {
// API方法
export const api = {
// 获取项目列表
getProjects: (): Promise<Project[]> => request<Project[]>('/projects'),
getProjects: (): Promise<Project[]> => request<Project[]>("/projects"),
// 上传项目
uploadProject: (formData: FormData): Promise<UploadResponse> =>
request<UploadResponse>('/upload', {
method: 'POST',
uploadProject: (formData: FormData): Promise<UploadResponse> => {
const API_BASE = getApiBase()
return fetch(`${API_BASE}/upload`, {
method: "POST",
body: formData,
headers: {}, // 让浏览器自动设置Content-Type
}),
}).then(async (response) => {
const data = await response.json()
if (!response.ok) {
throw new Error(data.error || "请求失败")
}
return data
})
},
// 切换项目状态
toggleProject: (slug: string): Promise<ToggleResponse> =>
toggleProject: (slug: string): Promise<ToggleResponse> =>
request<ToggleResponse>(`/projects/${slug}/toggle`, {
method: 'PATCH',
method: "PATCH",
}),
// 删除项目
deleteProject: (slug: string): Promise<{ message: string }> =>
deleteProject: (slug: string): Promise<{ message: string }> =>
request<{ message: string }>(`/projects/${slug}`, {
method: 'DELETE',
method: "DELETE",
}),
}