Is there a way to create new request object in a javascript policy?

Hi,

It is clear that the AssignMessage policy has the ability to create brand new request object, but is it possible to create one in the javascript code?

0 4 1,103
4 REPLIES 4

Not applicable

yes, you can create a new request object, which will be used to call an api inside the same javascript.

var myRequest = new Request();
myRequest.url = "http://www.example.com";
var exchangeObj = httpClient.send(myRequest);

Here's a more complete illustration, that uses the recommended callback mechanism.

  function onComplete(response, error) {
    if (response) {
      context.setVariable('example.status', response.status);
    }
    else {
      context.setVariable('example.error', 'Whoops: ' + error);
    }
  }


  var url = 'https://example.com/path1/' + id ;
  var headers = { 'ID-Index' : ix };
  var req = new Request(url, 'GET', headers);
  httpClient.send(req, onComplete);

or for a post, something like this:

var payload = JSON.stringify({
   foo : 'bar',
   whatever : 1234 
});
var headers = {
      'Content-Type' : 'application/json',
      'Authorization' : 'Bearer xyz'
    };
var url = 'https://example.com/path2';
var req = new Request(url, 'POST', headers, payload);


httpClient.send(req, onComplete);

Thank you very much for the detailed answers! And this request object couldn't replace the predefined in the context request variable, is this correct?

I.e I cannot do context.setVariable('request', new Request())

Nice day,

Pavlina

I don't know, I've never tried that. What are we solving for?

You can set the values on the existing request object. You can set the method, payload, headers, etc.