Get hands-on experience with 20+ free Google Cloud products and $300 in free credit for new customers.

JS script reading all response headers and iterate over them afterwards

I'm implementing a JS script on apigee gateway, triggered via a JS-policy

I'm reading the response headers like this  

const responseHeaders = context.getVariable('response.headers.names');
 
It's returning this 

[Access-Control-Allow-Origin, Content-Encoding, Content-Type, Date, Strict-Transport-Security, Transfer-Encoding, Vary, x-ms-middleware-request-id]

So fare so good 🙂 

nest step is to iterate over this array, but I had not luck achieving this.  

I tried to iterate over this like this

responseHeaders.forEach(header => {
   print(headers);
   }); 
responseHeaders type of :[object JavaObject]

I investigate the type of the responseHeaders const and it returns the above

I suspect that the responseHeaders const is of a type not known in JS and therefore it's not handled as a array. 

Any suggestions to solved ? 

Solved Solved
0 6 316
1 ACCEPTED SOLUTION

This solved it

 

const responseHeaderNamesArray = responseHeaderNames.substring(1, responseHeaderNames.length - 1).split(',').map(h => h.trim());
// Remove brackets [], split string by comma, Trim whitespace

responseHeaderNamesArray.forEach(element => {
  print(element+": "+context.getVariable('response.header.'+element));
  // ... perform need operation for each response header
});

output is
Access-Control-Allow-Origin:
Content-Encoding: gzip
Content-Type: application/json; charset=utf-8
Vary: Origin
...etc. 

 

 

View solution in original post

6 REPLIES 6
Top Solution Authors