diff --git a/web/modules/api.js b/web/modules/api.js index e48717e..4ac6969 100644 --- a/web/modules/api.js +++ b/web/modules/api.js @@ -49,6 +49,16 @@ const getMobile = () => { return value && String(value).trim() ? String(value).trim() : ''; }; +/** + * 从 URL 参数中获取 token + * @returns {string} token,不存在返回空字符串 + */ +const getToken = () => { + const params = new URLSearchParams(window.location.search || ''); + const value = params.get('token'); + return value && String(value).trim() ? String(value).trim() : ''; +}; + /** * 从 URL 参数中获取商户 ID * @returns {string} 商户 ID,不存在返回空字符串 @@ -97,6 +107,19 @@ const parsePaginatedResponse = (data) => { }; }; +/** + * 预处理请求 headers,添加 token + * @returns {Object} headers 对象 + */ +const buildHeaders = () => { + const headers = { 'Content-Type': 'application/json' }; + const token = getToken(); + if (token) { + headers['token'] = token; + } + return headers; +}; + /** * 通用 GET 请求 * @param {string} endpoint - API 端点 @@ -124,7 +147,9 @@ const get = async (endpoint, options = {}) => { url += (endpoint.includes('?') ? '&' : '?') + queryString; } - const response = await fetch(url); + const response = await fetch(url, { + headers: buildHeaders() + }); if (!response.ok) { throw new Error(`请求失败: ${response.status} ${response.statusText}`); } @@ -149,7 +174,7 @@ const post = async (endpoint, body, options = {}) => { const response = await fetch(url, { method: 'POST', - headers: { 'Content-Type': 'application/json' }, + headers: buildHeaders(), body: JSON.stringify(body) }); @@ -181,10 +206,7 @@ const patch = async (endpoint, body) => { const url = API_BASE + endpoint; const response = await fetch(url, { method: 'PATCH', - headers: { - 'Content-Type': 'application/json', - 'Accept': 'application/json' - }, + headers: buildHeaders(), body: JSON.stringify(body) }); @@ -209,7 +231,10 @@ const del = async (endpoint, options = {}) => { url += (endpoint.includes('?') ? '&' : '?') + 'soft=1'; } - const response = await fetch(url, { method: 'DELETE' }); + const response = await fetch(url, { + method: 'DELETE', + headers: buildHeaders() + }); if (!response.ok) { const errorText = await response.text(); throw new Error(errorText || `请求失败: ${response.status}`); @@ -435,6 +460,7 @@ window.ApiService = { API_BASE, getUserId, getMobile, + getToken, hasOnlyUserId, getMerchantId, buildUserQueryString,