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

Google Apps Script调用API时出现ReferenceError: URLSearchParams未定义,求解决方案

解决Google Apps Script中"ReferenceError: URLSearchParams is not defined"的问题

Google Apps Script的JavaScript运行环境基于旧版Rhino引擎,不支持ES6+的URLSearchParamsAPI,同时也不能直接用浏览器端的fetch函数——得改用GAS内置的UrlFetchApp工具处理HTTP请求。

以下是修改后的可运行代码:

function ApiTest() {
  const status = "watching";
  const num_watched_episodes = 10;
  const token = "MyTokenIsHere";
  const id = 50346;
  
  // 用普通对象存储请求参数,替代URLSearchParams
  const payload = {
    status: status,
    num_watched_episodes: num_watched_episodes
  };
  
  const url = `https://api.myanimelist.net/v2/anime/${id}/my_list_status`;
  
  const requestOptions = {
    method: "PATCH",
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    payload: payload // UrlFetchApp会自动将对象编码为表单格式
  };
  
  try {
    const response = UrlFetchApp.fetch(url, requestOptions);
    Logger.log('请求成功,响应内容: ' + response.getContentText());
  } catch (error) {
    Logger.log('请求失败,错误信息: ' + error.toString());
  }
}

关键修改点说明

  • 移除async关键字:UrlFetchApp.fetch是同步方法,不需要异步语法支持
  • 替换URLSearchParams:直接用普通对象存参数,UrlFetchApp会自动把它转成x-www-form-urlencoded格式的请求体
  • 替换fetch为UrlFetchApp.fetch:这是GAS官方提供的HTTP请求工具,适配其运行环境
  • 添加Content-Type头:明确告诉API请求体格式,确保参数能被正确解析
  • 加入错误捕获:用try-catch包裹请求逻辑,方便在日志里查看调试信息

如果需要手动拼接表单参数(比如处理特殊字符或自定义编码逻辑),可以用以下方式构建请求体:

const formBody = Object.entries(payload)
  .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
  .join('&');

然后把requestOptions里的payload换成formBody即可。

内容的提问来源于stack exchange,提问作者Red Reaper

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 18:15:43