得到代码422错误时转换cURL到谷歌应用程序脚本

xqnpmsa8  于 2023-03-03  发布在  其他
关注(0)|答案(1)|浏览(143)

文件内容如下:
使用code参数值向API中授权类型为authorization_code的OAuth令牌端点发出以下请求:

curl --location --request POST 'https://api.deliverr.com/oauth/v1/token' \\
--header 'Content-Type: application/x-www-form-urlencoded' \\
--data-urlencode 'code={received_code_value}' \\
--data-urlencode 'grant_type=authorization_code'

我尝试使用谷歌应用程序脚本,使代码如下

function testGetToken(){
  var url = "https://api.staging.deliverr.com/oauth/v1/token"
  /*const payload = {
      'code':'this is code',
      'grant-type':'authorization_code'
  };*/
  var headers = {
            "code": "this is code",
            "grant_type": "authorization_code",
            "Content-Type": "application/x-www-form-urlencoded"
        };
  const options = {
      'method': 'POST',
      'header': headers
      //'payload': payload
  };
  var response = UrlFetchApp.fetch(url, options);
  Logger.log(response.getContentText());

}

无论我把代码和grant_type放到有效负载还是头中,它们都返回相同的消息

Exception: Request failed for https://api.staging.deliverr.com returned code 422. 
Truncated server response: 
{"code":422,"message":"{"fields":{"request.grant_type":
{"message":"'grant_type' is required"}}}\n
Please refer to Deliverr API documentation... 
(use muteHttpExceptions option to examine full response)

我的代码是怎么回事?是urlencode的问题还是别的什么?如何让它工作?

s6fujrry

s6fujrry1#

我相信你的目标如下。

  • 您要将以下curl命令转换为Google Apps脚本。
curl --location --request POST 'https://api.deliverr.com/oauth/v1/token' \
  --header 'Content-Type: application/x-www-form-urlencoded' \
  --data-urlencode 'code={received_code_value}' \
  --data-urlencode 'grant_type=authorization_code'
  • 您已经确认了curl命令工作正常。

在这种情况下,下面的修改怎么样?

修改的脚本:

function testGetToken() {
  const url = "https://api.deliverr.com/oauth/v1/token";
  const payload = {
    'code': '{received_code_value}',
    'grant-type': 'authorization_code'
  };
  const options = { payload };
  const response = UrlFetchApp.fetch(url, options);
  Logger.log(response.getContentText());
}
  • payload与UrlFetchApp一起使用时,将自动使用POST方法。
  • 请求标头的默认内容类型为application/x-www-form-urlencoded
  • 在curl命令中,数据作为表单发送。

注:

  • 我认为上面的示例脚本的请求与您的curl命令相同,但是,如果出现错误,请再次确认您的'{received_code_value}''authorization_code'

参考:

  • 获取(url,参数)

相关问题