How do I call a POST request with form parameters using Javascript callout ?

 
0 4 26.7K
4 REPLIES 4

Hi @Ramnath,

I haven't tried this with form params, but there’s a good example showing how to do a POST with a JavaScript callout here, under “Example 3”.

For form parameters, you would probably need to change the way the Request object is created, so that it has Content-Type: application/x-www-form-urlencoded and a body with something like this:

parameter1=value1 & parameter2=value2

I'm guessing based on what's in the doc. Someone else might have a better answer if it doesn't work for you.

Will

Hi wwitman,

I tried using the following callout :

var url = "my-url";

var params = context.getVariable("request.content");

var headers = { 'Content-Type': 'application/x-www-form-urlencoded', };

var myRequest = new Request(url, "POST", headers, params);

var exchange = httpClient.send(myRequest);

exchange.waitForComplete();

if (exchange.isSuccess())

{ var responseObj = exchange.getResponse().content; }

else if (exchange.isError())

{ throw new Error(exchange.getError()); }

The params variable is populated as per the required form parameters, but I can't get any response.

Thanks

Ramnath

your code looks fine. There is a trailing comma in the headers array. That probably won't cause a problem, but I would remove it.

It's possible your backend server is not responding as expected. Check your assumptions.

Working example

function makeFormEncoder(hash){
  return function(key) {
    return encodeURIComponent(key) + '=' + encodeURIComponent(hash[key]);
  };
}


function getAccessToken() {
// eg,
// curl -X POST -i -H "Content-Type: application/x-www-form-urlencoded" \
//     "https://api.usergrid.com/management/token" \
//     -d 'grant_type=client_credentials&client_id=XXXX&client_secret=shhhh'
//
//
// {"access_token":"BAADBEEF","expires_in":604800,"application":"uuid-here"}


  var formValues = {
        'grant_type': 'password',
        'username': appSvcs.username,
        'password': appSvcs.password
      },
      pairs = Object.keys(formValues).map(makeFormEncoder(formValues)),
      headers = {
        'Content-Type' : 'application/x-www-form-urlencoded'
      },
      url = getAppServicesUrl() + '/token',
      req = new Request(url, 'POST', headers, pairs.join('&')),
      exchange = httpClient.send(req),
      responseBody;


  // Wait for the asynchronous POST request to finish
  exchange.waitForComplete();


  if (exchange.isError()) {
    throw { error: exchange.getError(), details: 'while authenticating'};
  }
  responseBody = JSON.parse(exchange.getResponse().content);


  if (responseBody.access_token) {
    return responseBody.access_token;
  }
  throw { error: exchange.getError(), details: 'while retrieving access_token'};
}