I can't get the sixth element from the header array

Why I can’t get the sixth element from the header array from the response, because it’s there?

I have the code in the pre-request scripts:

pm.sendRequest({
    url: pm.environment.get('baseUrl') + '/checkPhone',
    method: 'POST',
    header: {"Authorization": `Bearer ${pm.environment.get('accessToken')}`},
    body: {
        mode: 'raw',
        raw:JSON.stringify({
            "phone": `${randomInt}`,
            "sendAuthCode": false
        })
    }
}, (err, res) => {
    pm.test("Status code is 200", function () {
        res.code === 200;
    });
    
    console.log(res);
    console.log(res.status);
    console.log(res.code);
    console.log(res.header[6]);
});

Not exactly sure what is going on here, but the key is called “headers” despite what the console log is showing you.

Try the following…

console.log(res);
console.log(Object.keys(res));
console.log(res.headers);

The following is a basic sendRequest to Postman Echo.

The screenshot clearly shows the key as “header” when you console log the response, but when you console log the Object keys, its shows “headers” which does actually work.

** EDIT **

I think I do know what is going on here now, you haven’t parsed the response.

console.log(res.json());

If you do this, you will correctly see the key as “headers”.

Thank you for responding, but even with the headers key, it is not possible to get any of the array elements. As for the res.json() option, in this case I only get the response body without headers.

...
    console.log(res);
    console.log(res.headers);
    console.log(res.headers[6]);
    console.log(res.json());

I’ve had a look and you are correct. You can’t target any of the headers that way.

console.log(res);
console.log(typeof(res.headers));
console.log(res.headers);

pm.test('headers should be an array', () => {
    pm.expect(res.headers).to.be.an('array').that.is.not.empty;
});

image

I think I’ve seen this before. It’s technically not an array, its a list which is why you need to parse the response.

I guess whether the headers exist once you parse a response, will be down to the API specification.

On a normal request, you can use the pm.response method, but I’m not sure if there is an equivalent for sendRequest().

You could also try.

console.log(res.toJSON().header[6]);

Thanks a lot for the reply. I managed to extract the value I needed as follows:

console.log(res.toJSON().header[6].value);

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.