75 lines
1.9 KiB
JavaScript
75 lines
1.9 KiB
JavaScript
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;
|
||
}
|
||
};
|