Google Sheets调用API-Football v3触发Headers未定义错误求助
问题原因
你使用的示例代码是面向浏览器端JavaScript的运行环境编写的,而Google Sheets的脚本编辑器基于Google Apps Script(GAS) 运行,该环境不支持浏览器原生的Headers构造函数与fetch请求方法,因此触发了未定义报错。
修正后可直接在Google Sheets脚本中运行的代码
function soccer() { // 请求头直接使用普通对象即可,无需实例化Headers const requestHeaders = { "x-rapidapi-key": "替换为你自己的API密钥", "x-rapidapi-host": "v3.football.api-sports.io" }; const requestOptions = { method: 'GET', headers: requestHeaders, followRedirects: true }; try { // 使用GAS内置的UrlFetchApp发送请求,替代浏览器端的fetch const response = UrlFetchApp.fetch("https://v3.football.api-sports.io/fixtures?league=39&season=2021&timezone=America/New_York", requestOptions); const responseContent = response.getContentText(); // 执行结果可在脚本编辑器的执行日志中查看 console.log(responseContent); // 如需将结果写入当前表格A1单元格,可取消注释下方代码 // SpreadsheetApp.getActiveSheet().getRange(1, 1).setValue(responseContent); } catch (err) { console.log('请求出错', err); } }
运行注意事项
- 首次运行代码需要按照页面提示完成授权,允许脚本访问网络接口以及你的表格数据
- 接口返回的JSON格式数据可以通过
JSON.parse(responseContent)转换为对象,再提取对应字段写入表格指定位置
内容的提问来源于stack exchange,提问作者Brian Zollinhofer
相关产品推荐
相关产品推荐

