From f16e1d625acb699036a3215c62c23bcadc209307 Mon Sep 17 00:00:00 2001 From: canglan Date: Thu, 2 Apr 2026 01:44:27 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E4=BA=8C=E7=BB=B4=E7=A0=81?= =?UTF-8?q?=E7=94=9F=E6=88=90=E5=99=A8=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- js/common.js | 24 +++++++++++++++++++++--- pages/qrcode.php | 6 ++---- 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/js/common.js b/js/common.js index f9d3563..bee1ab4 100644 --- a/js/common.js +++ b/js/common.js @@ -27,11 +27,25 @@ async function apiRequest(endpoint, options = {}) { const baseUrl = window.API_BASE || '/api/v1'; const url = endpoint.startsWith('http') ? endpoint : `${baseUrl}${endpoint}`; + // 默认 headers const headers = { - 'Content-Type': 'application/json', ...options.headers }; + // 如果没有设置 Content-Type 且 body 是 URLSearchParams,不自动添加 + if (!options.headers || !options.headers['Content-Type']) { + if (options.body && options.body instanceof URLSearchParams) { + // 表单数据,不添加 JSON Content-Type + headers['Content-Type'] = 'application/x-www-form-urlencoded'; + } else if (options.body && typeof options.body === 'string') { + // 已经是字符串,不添加 + } else if (options.body && typeof options.body === 'object') { + // JSON 对象 + headers['Content-Type'] = 'application/json'; + options.body = JSON.stringify(options.body); + } + } + const token = getToken(); if (token) { headers['Authorization'] = `Bearer ${token}`; @@ -51,7 +65,7 @@ async function apiRequest(endpoint, options = {}) { return null; } - // 先获取响应文本,用于调试 + // 获取响应文本 const text = await response.text(); if (!response.ok) { @@ -65,7 +79,11 @@ async function apiRequest(endpoint, options = {}) { throw new Error(errorMsg); } - return JSON.parse(text); + try { + return JSON.parse(text); + } catch (e) { + return text; + } } catch (error) { console.error('API 请求错误:', error); throw error; diff --git a/pages/qrcode.php b/pages/qrcode.php index 52f9102..3fd3d7c 100644 --- a/pages/qrcode.php +++ b/pages/qrcode.php @@ -50,16 +50,14 @@ async function generateQR() { const size = parseInt(document.getElementById('size').value); try { + // 使用 URLSearchParams 发送表单数据 const formData = new URLSearchParams(); formData.append('content', content); formData.append('size', size); const data = await apiRequest('/qrcode/generate', { method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded' - }, - body: formData + body: formData // 不需要设置 headers,apiRequest 会自动处理 }); currentQRCode = data.qr_code;