From ee119d472fe34c0c3a78bf8e7e5777fd9101d4f6 Mon Sep 17 00:00:00 2001 From: imeepos Date: Tue, 13 Jan 2026 16:02:28 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=20fetch=20=E6=8B=A6?= =?UTF-8?q?=E6=88=AA=E5=99=A8=E6=AD=A3=E7=A1=AE=E5=A4=84=E7=90=86=20JSON?= =?UTF-8?q?=20=E8=AF=B7=E6=B1=82=E4=BD=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 正确处理不同类型的 headers(Headers 对象、数组、普通对象) - 自动序列化对象类型的请求体为 JSON 字符串 - 确保非 GET/HEAD 请求设置正确的 Content-Type - 修复登录请求体变成 [object Object] 的问题 Co-Authored-By: Claude --- lib/fetch-logger.ts | 42 ++++++++++++++++++++++++++++++++++-------- 1 file changed, 34 insertions(+), 8 deletions(-) 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) {