You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Excel Online脚本出现Line 15: Failed to fetch错误,请求排查解决

解决Excel Online脚本Line 15: Failed to fetch错误及数据解析问题

一、排查Failed to fetch错误原因及修复

1. 跨域资源共享(CORS)配置问题

Excel Online脚本运行在浏览器沙箱环境中,自定义接口必须配置正确的CORS响应头,允许Excel域名发起请求:

  • 在自定义链接的响应中添加以下HTTP头:
    Access-Control-Allow-Origin: https://excel.officeapps.live.com
    Access-Control-Allow-Methods: GET, OPTIONS
    Access-Control-Allow-Headers: Content-Type
    
    测试阶段可临时用*代替指定域名,生产环境建议配置具体Excel域名以保障安全。

2. 请求URL格式验证

确保{CUSTOM LINK}是完整的HTTP/HTTPS地址,拼接company和id后无格式错误。可通过脚本中的console.log(link)输出URL到Excel脚本控制台,复制该URL在浏览器中直接访问,确认接口能正常返回响应。

二、修复JSON响应格式问题

你提供的JSON响应末尾多了一个逗号,属于无效JSON格式,会导致后续解析失败:
原错误响应:

{"text":"individual text result","index":0,"logprobs":null,"finish_reason":"stop"},

修改为有效JSON:

{"text":"individual text result","index":0,"logprobs":null,"finish_reason":"stop"}

三、修正脚本中的数据解析逻辑

你的脚本期望响应是包含data字段的嵌套对象,但实际接口直接返回了JSONData结构,同时类型定义存在不匹配问题,需调整如下:

async function getairequest(company: string, id: string): Promise<string>{
  const link = encodeURI('{CUSTOM LINK}/' + company + '/' + id);

  console.log(link);
  const response = await fetch(link);

  // 直接解析为JSONData类型,无需嵌套的data字段
  const data: JSONData = await response.json();

  console.log(JSON.stringify(data));

  return data.text;
}

// 修正logprobs的类型定义,允许null值
interface JSONData {
  text: string;
  index: number;
  logprobs: string | null;
  finish_reason: string;
}

四、额外调试建议

  • 打开Excel脚本编辑器的控制台(右上角控制台图标),查看console.log(link)输出的URL,手动访问确认接口状态。
  • 添加错误捕获逻辑,打印详细错误信息便于排查:
async function getairequest(company: string, id: string): Promise<string>{
  const link = encodeURI('{CUSTOM LINK}/' + company + '/' + id);

  console.log(link);
  try {
    const response = await fetch(link);
    if (!response.ok) {
      throw new Error(`HTTP错误! 状态码: ${response.status}`);
    }
    const data: JSONData = await response.json();
    return data.text;
  } catch (error) {
    console.error('请求或解析错误:', error);
    return '获取数据失败'; // 将错误提示写入单元格
  }
}

内容的提问来源于stack exchange,提问作者Kay B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 13:26:01