JS调用API报错Authorization failed: Unexpected end of input怎么解决?
解决JavaScript调用API时的"Unexpected end of input"错误
问题重现
点击按钮调用getOdds()函数时,控制台报错:
Authorization failed : Unexpected end of input
相关代码如下:
HTML按钮代码
<button onclick="event.preventDefault(); getOdds()">Print odds</button>
原JS代码
function getOdds() { const sportsKey = prompt("Enter the sports key:"); const region = prompt("Enter the region (choices = uk, us, us2, eu, au):"); const market = prompt("Enter the market (choices = h2h, spreads, totals, outrights):"); const apiKey = 'APIKEY'; let headers = new Headers(); headers.append('Content-Type', 'application/json'); headers.append('Accept', 'application/json'); headers.append('Access-Control-Allow-Origin', '*'); headers.append('Access-Control-Allow-Credentials', 'true'); headers.append('GET', 'POST', 'OPTIONS'); headers.append('apikey','apikey'); fetch('https://apiurl/'+sportsKey+'/odds?apiKey='+apiKey+'®ions='+region+'&markets='+market+'', { mode: 'no-cors', credentials: 'include', method: 'GET', headers: headers }) .then(response => response.json()) .then(json => console.log(json)) .catch(error => console.log('Authorization failed : ' + error.message)); }
错误原因分析
mode: 'no-cors'限制响应读取:
该模式下浏览器返回无法解析的opaque响应,调用response.json()必然失败,触发"Unexpected end of input"错误。- 无效的CORS头设置:
Access-Control-Allow-Origin、Access-Control-Allow-Credentials这类头是服务器端专属配置,前端设置完全无效,还可能干扰请求逻辑。 - Header语法错误:
headers.append('GET', 'POST', 'OPTIONS');不符合Headers.append(key, value)的语法规则,属于无效代码。 - API Key配置错误:
Header里的apikey值写死为'apikey',未使用定义好的apiKey常量;同时URL参数已传递密钥,存在重复配置问题。
修正后的代码
function getOdds() { const sportsKey = prompt("Enter the sports key:"); const region = prompt("Enter the region (choices = uk, us, us2, eu, au):"); const market = prompt("Enter the market (choices = h2h, spreads, totals, outrights):"); const apiKey = 'APIKEY'; // 替换为你的真实API密钥 let headers = new Headers(); // 只保留必要请求头 headers.append('Accept', 'application/json'); // 若API要求通过Header传密钥,取消下方注释并确保值正确 // headers.append('apikey', apiKey); // 用模板字符串简化URL拼接 const apiUrl = `https://apiurl/${sportsKey}/odds?apiKey=${apiKey}®ions=${region}&markets=${market}`; fetch(apiUrl, { method: 'GET', headers: headers // 服务器无需凭证则移除该行;如需凭证,确保服务器配置对应CORS头 // credentials: 'include' }) .then(response => { // 先校验响应状态是否正常 if (!response.ok) { throw new Error(`HTTP错误! 状态码: ${response.status}`); } return response.json(); }) .then(json => console.log(json)) .catch(error => console.log('请求失败 : ' + error.message)); }
额外注意事项
- 确保API服务器已配置正确的CORS策略,允许你的前端域名跨域请求。若未配置,需使用代理服务器转发请求(如本地Node.js代理、Nginx反向代理),否则浏览器会拦截请求。
- 确认
APIKEY替换为真实密钥,且apiurl为正确的API地址。 - 若API要求通过Header而非URL参数传递密钥,取消
headers.append('apikey', apiKey)注释,并移除URL中的apiKey=${apiKey}参数。
内容的提问来源于stack exchange,提问作者Hamza Zafeer
相关产品推荐
相关产品推荐

