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

在Google Apps Script中获取受CORS保护的API超时问题求助

排查Google Apps Script调用NSE API超时问题及数据导入方案

核心问题拆解

请求超时的根源集中在以下几点:

  • 冗余请求头干扰:authority、path、scheme属于UrlFetchApp自动处理的字段,手动添加会导致请求格式异常;sec-fetch-*、sec-ch-ua-mobile是浏览器专属CORS头,服务器会识别出非真实浏览器请求,触发拦截或延迟响应。
  • 硬编码Cookie过期:你使用的cookie包含nseappid、会话ID等临时凭证,这类值会定期失效,直接硬编码会导致请求被服务器拒绝,最终超时。
  • 重定向设置错误:followRedirects: false会阻止请求跟随服务器的3xx重定向,导致请求无法完成。

修正后的可运行代码

先获取有效会话凭证,再发起API请求并写入Google Sheet:

function fetchNSEData() {
  // 1. 访问NSE主页获取有效会话Cookie
  const baseUrl = "https://www.nseindia.com";
  const baseOptions = {
    method: "GET",
    headers: {
      "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36",
      "Accept-Language": "en-US,en;q=0.9"
    },
    muteHttpExceptions: true,
    followRedirects: true
  };
  
  const baseResponse = UrlFetchApp.fetch(baseUrl, baseOptions);
  const cookies = baseResponse.getAllHeaders()["Set-Cookie"];

  // 2. 构造API请求
  const apiUrl = "https://www.nseindia.com/api/liveEquity-derivatives?index=nse50_fut";
  const apiOptions = {
    method: "GET",
    headers: {
      "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36",
      "Accept-Language": "en-US,en;q=0.9",
      "Cookie": cookies.join("; "),
      "Referer": baseUrl
    },
    muteHttpExceptions: true,
    followRedirects: true
  };

  // 3. 发起请求并处理数据
  try {
    const apiResponse = UrlFetchApp.fetch(apiUrl, apiOptions);
    const jsonData = JSON.parse(apiResponse.getContentText());
    
    // 4. 将数据写入Google Sheet
    const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
    sheet.clearContents();
    
    if (jsonData.data && jsonData.data.length > 0) {
      // 写入表头
      const headers = Object.keys(jsonData.data[0]);
      sheet.getRange(1, 1, 1, headers.length).setValues([headers]);
      
      // 写入数据行
      const rows = jsonData.data.map(item => headers.map(header => item[header]));
      sheet.getRange(2, 1, rows.length, headers.length).setValues(rows);
    }
    console.log("数据导入完成");
  } catch (e) {
    console.error("请求失败:", e.toString());
    SpreadsheetApp.getActiveSpreadsheet().toast("数据获取失败,请稍后重试");
  }
}

关键注意事项

  • UA保持真实:使用最新桌面端User-Agent,避免用过时的移动端UA,降低被反爬拦截的概率。
  • 控制请求频率:NSE服务器有反爬机制,短时间多次请求会被封禁,建议通过Google Apps Script的时间触发器设置间隔请求(比如每5分钟一次)。
  • 动态更新Cookie:每次请求前先访问NSE主页获取最新Cookie,避免硬编码过期凭证。

内容的提问来源于stack exchange,提问作者I'm RamOP

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 07:25:23