javascript - API Post request in Google App Script not working - Stack Overflow

I managed to do the API POST request through Postman but once modified for Google App Script it doesn&#

I managed to do the API POST request through Postman but once modified for Google App Script it doesn't work. I think it might be related to the body format, I can't replicate the new URLSearchParams() object in GAS (I'm sending a JSON I believe).

Thanks.

Postman (working) - JavaScript Fetch

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");

var urlencoded = new URLSearchParams();
urlencoded.append("client_id", "XXXX");
urlencoded.append("client_secret", "XXXX");
urlencoded.append("grant_type", "client_credentials");

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: urlencoded,
  redirect: 'follow'
};

fetch(";, requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

CURL

curl --location --request POST '' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'client_id=XXXX' \
--data-urlencode 'client_secret=XXXX' \
--data-urlencode 'grant_type=client_credentials'

My faulty GAS version :(

function getCostAU() {
  
  var myHeaders = {"Accept": "application/json",
                   "Content-Type": "application/x-www-form-urlencoded"};
  
  var myPayload = {"client_id" : "XXXX",
                   "client_secret" : "XXXX",
                   "grant_type" : "client_credentials"};
  
  var requestOptions = {
    method: 'POST',
    headers: myHeaders,
    body: myPayload,
    redirect: 'follow',
  };
    
  var url = ";;
  var result = JSON.parse(UrlFetchApp.fetch(url, requestOptions).getContentText());
  var access_token = result.access_token;
};

I managed to do the API POST request through Postman but once modified for Google App Script it doesn't work. I think it might be related to the body format, I can't replicate the new URLSearchParams() object in GAS (I'm sending a JSON I believe).

Thanks.

Postman (working) - JavaScript Fetch

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");

var urlencoded = new URLSearchParams();
urlencoded.append("client_id", "XXXX");
urlencoded.append("client_secret", "XXXX");
urlencoded.append("grant_type", "client_credentials");

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: urlencoded,
  redirect: 'follow'
};

fetch("https://apigateway.criteo./oauth2/token", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

CURL

curl --location --request POST 'https://apigateway.criteo./oauth2/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'client_id=XXXX' \
--data-urlencode 'client_secret=XXXX' \
--data-urlencode 'grant_type=client_credentials'

My faulty GAS version :(

function getCostAU() {
  
  var myHeaders = {"Accept": "application/json",
                   "Content-Type": "application/x-www-form-urlencoded"};
  
  var myPayload = {"client_id" : "XXXX",
                   "client_secret" : "XXXX",
                   "grant_type" : "client_credentials"};
  
  var requestOptions = {
    method: 'POST',
    headers: myHeaders,
    body: myPayload,
    redirect: 'follow',
  };
    
  var url = "https://apigateway.criteo./oauth2/token";
  var result = JSON.parse(UrlFetchApp.fetch(url, requestOptions).getContentText());
  var access_token = result.access_token;
};
Share Improve this question edited Nov 13, 2022 at 19:57 Wicket 38.7k9 gold badges80 silver badges195 bronze badges asked Oct 16, 2020 at 4:04 fasitofasito 1001 silver badge6 bronze badges 1
  • @TheMaster Thanks. You mean that the URLSearchParams() object can be replicated in GAS with a encodeURIComponent ? – fasito Commented Oct 16, 2020 at 4:19
Add a ment  | 

1 Answer 1

Reset to default 9

Issues:

  • body is not a valid key in options argument. You should use payload instead.

  • redirect is not a valid key in options argument

  • Currently, URLSearchParams is not supported in apps script.

Solution:

  • Change body to payload

  • Re-create the payload object as a query string. For example, payload:{x:1,y:2} should be changed to x=1&y=2.

Snippet:

  • Payload object to query params:

function objectToQueryParams(obj) {
  return (
    Object.entries(obj)
      .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
      .join('&')
  );
}

const myPayload = {"client_id" : "XXXX",
               "client_secret" : "XXXX",
               "grant_type" : "client_credentials"};
  
console.log(objectToQueryParams(myPayload));

  • Valid requestOption:
  const requestOptions = {
    /**@see https://developers.google./apps-script/reference/url-fetch/url-fetch-app#fetch(String,Object)*/
    method: 'POST',
    headers: myHeaders,
    payload: objectToQueryParams(myPayload),//modified
    //or just payload: myPayload will work as mentioned in the ments below
    //redirect: 'follow',//removed 
    followRedirects: true
  };
  • Full script:

/**Mock UrlFetchApp library*/
const UrlFetchApp = {
  fetch: () => ({
    getContentText: () =>
      '{"access_token":"jghlfdjlfwqwXjogsfshbkgetrwuguerjyrcyfxuux=="}',
  }),
};
getCostAU(); //call function
//Mock end


function getCostAU() {
  const myHeaders = {
    Accept: 'application/json',
    'Content-Type': 'application/x-www-form-urlencoded',
  };

  const myPayload = {
    client_id: 'XXXX',
    client_secret: 'XXXX',
    grant_type: 'client_credentials',
  };

  function objectToQueryParams(obj) {
    return Object.entries(obj)
      .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
      .join('&');
  }

  const requestOptions = {
    /**@see https://developers.google./apps-script/reference/url-fetch/url-fetch-app#fetch(String,Object)*/
    method: 'POST',
    headers: myHeaders,
    payload: objectToQueryParams(myPayload), //modified
    //or just payload: myPayload will work as mentioned in the ments below
    //redirect: 'follow',//removed
    followRedirects: true,
  };

  const url = 'https://apigateway.criteo./oauth2/token';
  const result = JSON.parse(
    UrlFetchApp.fetch(url, requestOptions).getContentText()
  );
  const access_token = result.access_token;
  console.log(access_token);
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744300201a4567463.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信