Extract header values from response header

Hi Team,

Find this article Response

When I try with the below code to extract the value of the Location from the response header I’m getting undefined message.
res.headers.Location
image

The response contains the value
image

Is there any way to extract values through the response header?

Hi @Gerard
Will this answer help you?

import { check } from 'k6';
import http from 'k6/http';

export default function () {
  const res = http.get('https://k6.io');

  console.log(res.headers['Content-Type']);

  if(res.headers['Content-Type'] == 'text/html') {
    console.log(true);

  } else {

    console.log(false);
  }

  check(res, {
    'status is 200': (r) => r.status === 200,
  });
}
1 Like

Hi @PaulM ,

I tried your option but still, it says undefined.

Response with --http-debug

From the code
image

Output says
image

You can also try:

import { check } from 'k6';
import http from 'k6/http';

export default function () {
  const res = http.get('https://k6.io');


  let myResourceURL = res.headers['Content-Type'];

  console.log('Result: ' + myResourceURL);

  check(res, {
    'status is 200': (r) => r.status === 200,
  });
}

In your code:

let myResourceURL = srchLightres.headers['Expect-Ct']; (Pay attention that **t**)
console.log('The resource url was' + myResourceURL)
1 Like

@PaulM I used the template literals. But if I changed the way you suggest also it gets an undefined message.

image

and the Output again like
image

@Gerard Change headers name:
srchLightres.headers[‘Expect-Ct’]; (Pay attention that t)

1 Like

Thanks, @PaulM Good catch. When I changed it to Expect-ct it works fine.

But when I try to capture another header value it shows undefined.

Any Tips to overcome this issue.

@Gerard Now it’s difficult to say what’s the problem, but if we are using this loop:

const res = http.get('https://k6.io');
  for (const p in res.headers) {
    if (res.headers.hasOwnProperty(p)) {
      console.log(p + ' : ' + res.headers[p]);
    }
  }

And find headers Location then this variable will definitely appear here res.headers[‘Location’]

1 Like