diff --git a/lib/fetch-logger.ts b/lib/fetch-logger.ts index 0fc004e..0263074 100644 --- a/lib/fetch-logger.ts +++ b/lib/fetch-logger.ts @@ -37,17 +37,43 @@ export const createFetchWithLogger = (options: FetchLoggerOptions = {}) => { // 使用统一的 Token 存储键 const token = await storage.getItem(TOKEN_KEY) - if (token) { - init = { - ...init, - headers: { - ...init?.headers, - authorization: `Bearer ${token}`, - }, + // 确保 headers 是一个对象 + const headers: Record = {} + if (init?.headers) { + if (init.headers instanceof Headers) { + init.headers.forEach((value, key) => { + headers[key] = value + }) + } else if (Array.isArray(init.headers)) { + init.headers.forEach(([key, value]) => { + headers[key] = value as string + }) + } else { + Object.assign(headers, init.headers) } } - const response = await originalFetch(input, init) + // 添加 Bearer Token + if (token) { + headers['authorization'] = `Bearer ${token}` + } + + // 确保 Content-Type 正确设置 + if (method !== 'GET' && method !== 'HEAD' && !headers['Content-Type']) { + headers['Content-Type'] = 'application/json' + } + + // 序列化请求体(如果是对象) + let body = init?.body + if (body && typeof body === 'object' && !(body instanceof FormData) && !(body instanceof URLSearchParams)) { + body = JSON.stringify(body) + } + + const response = await originalFetch(input, { + ...init, + headers, + ...(body !== undefined && { body }), + }) // 401 未授权处理 if (response.status === 401 && !isRedirecting) {