Files
AI-Chat/public/assets/js/api.js
2026-05-06 18:25:44 +08:00

75 lines
1.9 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
const api = {
async request(url, options = {}) {
const token = Storage.getToken();
const headers = {
'Content-Type': 'application/json',
...(token ? { 'Authorization': 'Bearer ' + token } : {}),
...options.headers
};
const response = await fetch('/api' + url, {
...options,
headers
});
// 401 自动跳转登录
if (response.status === 401) {
Storage.clearToken();
window.location.href = '/login.php';
throw new Error('请先登录');
}
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || '请求失败');
}
return data;
},
get(url) {
return this.request(url, { method: 'GET' });
},
post(url, data) {
return this.request(url, {
method: 'POST',
body: JSON.stringify(data)
});
},
put(url, data) {
return this.request(url, {
method: 'PUT',
body: JSON.stringify(data)
});
},
delete(url) {
return this.request(url, { method: 'DELETE' });
},
// 文件上传(不用 JSON Content-Type
async upload(url, formData) {
const token = Storage.getToken();
const headers = token ? { 'Authorization': 'Bearer ' + token } : {};
const response = await fetch('/api' + url, {
method: 'POST',
headers,
body: formData
});
if (response.status === 401) {
Storage.clearToken();
window.location.href = '/login.php';
throw new Error('请先登录');
}
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || '上传失败');
}
return data;
}
};