Set Multiple headers in Javascript httpclient

Not applicable

How do I set multiple headers in javascript httpclient request? I have the below code it doesnt set the values properly.

var headers = {'Content-Type':'application/json', 'Accept':'application/json', 'Cache-Control':'no-cache'};

var auditors = new Request();

auditors.url = "https://demo.api.confirmation.com/auditor";

auditors.headers = headers;

var auditor = httpClient.send(auditors);

context.setVariable("auditorsResponse",auditor.code);

I get the auditorsResponse as org.mozilla.javascript.Undefined@25ef85d5

0 5 16.3K
5 REPLIES 5

The send method returns an exchange object, not a response object. You can't get the response code the way you have it coded.

See http://docs.apigee.com/api-services/reference/javascript-object-model#makingjavascriptcalloutswithht...

Hi Carlos,

I have updated the code, but I believe the Headers are not being passed as expected.

var headers = {'Content-Type':'application/json', 'Accept':'application/json', 'Cache-Control':'no-cache'};

var auditors = new Request();

auditors.url = "https://demo.api.confirmation.com/auditor";

auditors.headers = headers;

var auditor = httpClient.send(auditors), response, status;

auditor.waitForComplete();

if (!auditor.isSuccess()) { throw 'Error contacting auditors web service'; }

// We got a response. Parse the JSON into a JavaScript object.

auditorsResponse = auditor.getResponse().content.asJSON;

response.content = auditor.getResponse().content;

response.code = auditor.getResponse().status;

I get an 401 error due to missing headers.

If I try that request via curl I get 401 as well, but maybe you've cut out the secret bit for handling auth.

Regardless, here's a chunk of code that hits httpbin and passes in some headers. The response will contain the headers the service saw.. I've verified the FOO header is present, so headers are being set correctly.

var headers = {'FOO':'foo', 'Content-Type':'application/json', 'Accept':'application/json', 'Cache-Control':'no-cache'}
var url = "http://httpbin.org/headers"
var req = new Request(url, "GET", headers);
var exchange = httpClient.send(req);
exchange.waitForComplete()
var r = exchange.getResponse()
context.setVariable("auditorsHeaders",r.content);


Thank you Carlos, this seems to work now.

Only change is that, I dont think the headers can be assigned to the variable req as variable. those need to be defined in the Variable Definition.

I have made the change as you suggested and it works!

Not applicable

Hi @Pranay Aitha

I am also facing the same kind of issue in setting up the headers in javascript.

In your last comment you mentioned saying that after carlos suggestion you have tried it and it worked for you.

Even I am trying the same,but it's still giving 401 error it beacuse the headers are not set correctly in javascript.

Can you please give the code which you have tried.

Thanks in adavance.