添加API-Key请求头后API调用耗时过长,求优化方案
问题描述
我在向请求中添加'API-Key': 'xxxxxxxxx'这类额外请求头时,发现请求耗时明显增加。以下是Chrome中执行同一请求的两张截图:
带额外请求头时
不带额外请求头时
请问如何消除这部分额外等待时间?
测试代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>API Calls</title> <script> async function fetchApi(url, headers) { const response = await fetch(url, { method: 'GET', headers: headers }); const data = await response.json(); return data; } async function callApis() { const apiCalls = [ { name: 'Random User', url: 'https://randomuser.me/api/', headers: { 'accept': 'application/json', 'API-Key': 'xxxxxxxxx' } }, ]; const resultsContainer = document.getElementById('results'); resultsContainer.innerHTML = ''; for (const api of apiCalls) { const startTime = performance.now(); // Start timing const data = await fetchApi(api.url, api.headers); const endTime = performance.now(); // End timing const duration = endTime - startTime; // Calculate duration resultsContainer.innerHTML += `<h3>${api.name}</h3><pre>${JSON.stringify(data, null, 2)}</pre><p>Duration: ${duration.toFixed(2)} ms</p>`; } } // Call the APIs when the window loads window.onload = callApis; </script> </head> <body> <h1>API Calls Results</h1> <div id="results"></div> </body> </html>
问题分析与解决办法
核心原因
添加自定义API-Key请求头触发了CORS预检请求(OPTIONS请求):浏览器会先发送一次OPTIONS请求到服务器,确认服务器是否允许携带这个自定义头的请求,得到许可后才会发送真正的GET请求。这额外的一次请求就是耗时增加的根源。而不带自定义头时,请求属于浏览器认定的"简单请求",会直接发送GET请求,无需预检。
解决办法
- 服务器端配置CORS,允许自定义头并缓存预检结果
- 在服务器的CORS响应头中添加:
Access-Control-Allow-Headers: API-Key,明确告知浏览器允许客户端携带API-Key头Access-Control-Max-Age: 86400,设置预检请求的缓存时长(比如24小时),避免每次请求都重复触发预检
- 在服务器的CORS响应头中添加:
- 改用其他认证方式(若API支持)
- 将API密钥放在URL参数中(注意:此方式安全性较低,仅适用于非敏感场景)
- 使用Cookie认证(需确保跨域Cookie的相关配置正确)
- 部署同域代理服务器
- 在前端同域名下搭建一个代理,由代理转发请求并添加
API-Key头,这样前端请求属于同源请求,不会触发CORS预检
- 在前端同域名下搭建一个代理,由代理转发请求并添加
内容的提问来源于stack exchange,提问作者Sameh Serag
相关产品推荐
相关产品推荐

