将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()); }
补充说明:
- 务必将
your_received_code_value替换为实际从授权流程中获取到的code值。 muteHttpExceptions: true建议保留,遇到错误时能查看完整的服务器返回信息,便于排查问题。- UrlFetchApp会自动对对象类型的payload进行URL编码,效果与curl的
--data-urlencode一致,无需手动处理编码。
内容的提问来源于stack exchange,提问作者CK4wyzworks
相关产品推荐
相关产品推荐

