fix: centralize upload authorization headers
This commit is contained in:
1 parent
5314d60f53
commit
593e766596
1 file changed
+6
-4
@@ -3,15 +3,17 @@
|
|||||||
// ============================================================
|
// ============================================================
|
||||||
let token = localStorage.getItem('forumlify-token') || null;
|
let token = localStorage.getItem('forumlify-token') || null;
|
||||||
|
|
||||||
|
function getAuthHeaders() {
|
||||||
|
return token ? { 'Authorization': 'Bearer ' + token } : {};
|
||||||
|
}
|
||||||
|
|
||||||
function apiFetch(path, options = {}) {
|
function apiFetch(path, options = {}) {
|
||||||
const url = CONFIG.API_BASE_URL + path;
|
const url = CONFIG.API_BASE_URL + path;
|
||||||
const headers = {
|
const headers = {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
|
...getAuthHeaders(),
|
||||||
...(options.headers || {})
|
...(options.headers || {})
|
||||||
};
|
};
|
||||||
if (token) {
|
|
||||||
headers['Authorization'] = 'Bearer ' + token;
|
|
||||||
}
|
|
||||||
return fetch(url, {
|
return fetch(url, {
|
||||||
...options,
|
...options,
|
||||||
headers
|
headers
|
||||||
@@ -85,7 +87,7 @@ const API = {
|
|||||||
formData.append('file', file);
|
formData.append('file', file);
|
||||||
const response = await fetch(CONFIG.API_BASE_URL + '/upload', {
|
const response = await fetch(CONFIG.API_BASE_URL + '/upload', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: token ? { 'Authorization': 'Bearer ' + token } : {},
|
headers: getAuthHeaders(),
|
||||||
body: formData
|
body: formData
|
||||||
});
|
});
|
||||||
const data = await response.json().catch(() => ({ error: '上传响应无效' }));
|
const data = await response.json().catch(() => ({ error: '上传响应无效' }));
|
||||||
|
|||||||
Reference in new issue
Block a user