14 lines
769 B
JavaScript
14 lines
769 B
JavaScript
export async function api(path, options = {}) {
|
|
const binaryBody = options.body instanceof ArrayBuffer || options.body instanceof Blob || options.body instanceof FormData;
|
|
const response = await fetch(path, {
|
|
credentials: 'same-origin',
|
|
headers: { ...(options.body && !binaryBody ? { 'Content-Type': 'application/json' } : {}), ...options.headers },
|
|
...options,
|
|
body: options.body && typeof options.body !== 'string' && !binaryBody ? JSON.stringify(options.body) : options.body
|
|
});
|
|
const type = response.headers.get('content-type') || '';
|
|
const data = type.includes('application/json') ? await response.json() : await response.text();
|
|
if (!response.ok) throw new Error(data?.message || '操作未完成,请稍后重试');
|
|
return data;
|
|
}
|