Files
Nilai_Clock/src/api.js
T
sudomarcma 5e3015ba4f refactor(api): 统一前端API调用使用apiFetch并优化错误处理
refactor: 替换直接fetch调用为apiFetch以统一处理错误和响应
fix(server): 改进QR码验证的错误消息和密码哈希处理
2025-06-26 11:45:14 +08:00

32 lines
793 B
JavaScript

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL
export async function apiFetch(endpoint, options = {}) {
const token = sessionStorage.getItem('token')
const defaultHeaders = {
'ngrok-skip-browser-warning': 'true',
'Content-Type': 'application/json',
...options.headers,
}
if (token) {
defaultHeaders['Authorization'] = `Bearer ${token}`
}
const response = await fetch(`${API_BASE_URL}${endpoint}`, {
...options,
headers: defaultHeaders,
})
if (!response.ok) {
// Try to parse the error response body from the server
const errorData = await response.json()
throw new Error(errorData.message || `API call failed with status: ${response.status}`)
}
if (response.status === 204) {
return null
}
return response.json()
}