async function apiFetch(path, options) { const opts = options || {}; const headers = Object.assign({}, opts.headers || {}); if (opts.body && !headers['Content-Type']) { headers['Content-Type'] = 'application/json'; } const response = await fetch(path, { method: opts.method || 'GET', headers: headers, body: opts.body ? JSON.stringify(opts.body) : undefined, credentials: 'same-origin' }); let data = null; try { data = await response.json(); } catch (e) { data = {}; } if (!response.ok) { const error = new Error((data && data.error) || '请求失败: ' + response.status); error.status = response.status; throw error; } return data; } function apiGetMe() { return apiFetch('/api/me'); } function apiLogin(username, password) { return apiFetch('/api/login', { method: 'POST', body: { username: username, password: password } }); } function apiRegister(username, password, displayName) { return apiFetch('/api/register', { method: 'POST', body: { username: username, password: password, displayName: displayName } }); } function apiLogout() { return apiFetch('/api/logout', { method: 'POST' }); } function apiChangePassword(data) { return apiFetch('/api/change-password', { method: 'POST', body: data }); } function apiGetEntries() { return apiFetch('/api/entries'); } function apiAddEntry(data) { return apiFetch('/api/entries', { method: 'POST', body: data }); } function apiUpdateEntry(id, data) { return apiFetch('/api/entries/' + id, { method: 'PUT', body: data }); } function apiDeleteEntry(id) { return apiFetch('/api/entries/' + id, { method: 'DELETE' }); } function apiGetStats() { return apiFetch('/api/entries/stats'); } function apiGetVocabulary() { return apiFetch('/api/vocabulary'); } function apiAddVocabulary(data) { return apiFetch('/api/vocabulary', { method: 'POST', body: data }); } function apiDeleteVocabulary(id) { return apiFetch('/api/vocabulary/' + id, { method: 'DELETE' }); } function apiGetTranslationSettings() { return apiFetch('/api/settings/translation'); } function apiSaveTranslationSettings(data) { return apiFetch('/api/settings/translation', { method: 'PUT', body: data }); } function apiTranslate(data) { return apiFetch('/api/translate', { method: 'POST', body: data }); } function apiAdminUsers() { return apiFetch('/api/admin/users'); } function apiAdminCreateUser(data) { return apiFetch('/api/admin/users', { method: 'POST', body: data }); } function apiAdminSetStatus(id, isActive) { return apiFetch('/api/admin/users/' + id + '/status', { method: 'PUT', body: { isActive: isActive } }); } function apiAdminDeleteUser(id) { return apiFetch('/api/admin/users/' + id, { method: 'DELETE' }); } function apiAdminResetPassword(id, password) { return apiFetch('/api/admin/users/' + id + '/password', { method: 'PUT', body: { password: password } }); }