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

将cURL转为Google Apps Script时遭遇422错误,求解决方案

解答

你的代码存在三个核心问题:

  • 参数位置与拼写错误:OAuth要求grant_type和code必须放在请求体(payload)中,且你之前写的grant-type是错误的,应该是grant_type(下划线而非横杠)。
  • Header配置错误:options里的配置项是headers(复数),你写成了header,导致Header设置完全无效;另外UrlFetchApp在传递对象类型payload时,会自动设置Content-Type为application/x-www-form-urlencoded,无需手动添加。
  • 参数存放错误:将code和grant_type放在Header里不符合OAuth接口的要求,这些参数属于请求体内容。

修复后的代码如下:

function testGetToken(){
  var url = "https://api.staging.deliverr.com/oauth/v1/token";
  // 正确构造请求体参数,注意grant_type的下划线
  const payload = {
      'code': 'your_received_code_value', // 替换为实际获取的授权码
      'grant_type': 'authorization_code'
  };
  const options = {
      'method': 'POST',
      'payload': payload,
      'muteHttpExceptions': true // 开启后可查看完整错误响应,方便调试
  };
  var response = UrlFetchApp.fetch(url, options);
  Logger.log(response.getContentText());
}

补充说明:

  1. 务必将your_received_code_value替换为实际从授权流程中获取到的code值。
  2. muteHttpExceptions: true建议保留,遇到错误时能查看完整的服务器返回信息,便于排查问题。
  3. UrlFetchApp会自动对对象类型的payload进行URL编码,效果与curl的--data-urlencode一致,无需手动处理编码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 08:01:34