Max
Max

Reputation: 1487

Postman pre-request script: Can't access header from response

I am writing the following pre-request Script to get my JWT for authentication:

pm.sendRequest(echoPostRequest, function (err, res) {
    console.log(err, res, typeof res);
    if(err === null){
        console.log(res.header)
        // var authHeader = res.header.find(v => {v.key === 'Authorization'})
    }
});

This is what the console output currently looks like:

null, {id: "4ba2b741-316e-454d-b896-eab3aef74ae2", status: "OK", code: 200…}, object
undefined 
OK

// If you enlarge the opbject it looks like the following:

id: "4ba2b741-316e-454d-b896-eab3aef74ae2"
status: "OK"
code: 200
header: [10] <--- There are my headers ?!
stream: {…}
cookie: [0]
responseTime: 121
responseSize: 0

The problem is I can not access the header array the script always tells me it is undefined, same if I try the access the cookie array. But I can access every other single property, maybe it's because header and cookie are arrays? I don't know. Any ideas what I am doing wrong and how I can get my Authorization header?

Upvotes: 2

Views: 1558

Answers (2)

Rohim Chou
Rohim Chou

Reputation: 1269

Use res.headers.get('keyName') instead.

Response object from pm.sendRequest() has a headers member of type HeaderList. The HeaderList offer a get(key) method to acquire the header value by key.

See postman documentation for more details.

Upvotes: 0

Max
Max

Reputation: 1487

I think the Problem must be a bug, my workaround is to stringify and parse the object as json, than the headers are accessible.

r = JSON.parse(JSON.stringify(res))

Upvotes: 2

Related Questions