Unable to read header value for a request that is sent in Pre-req

Hey, I need to get the value of one of the attribute in response header. The request is sent using the script in pre-req.
The error message that I receive is “There was an error in evaluating the Pre-request Script: Error: Cannot read property ‘headers’ of undefined”.

I am using “pm.response.headers.get(“Location”)” to get the value.

Hi @baljindernohra, Welcome to community :wave:

Kindly refer the below post which has a similar question and check if this answers your question.

Hey @baljindernohra, welcome!

This can certainly seem tricky since you’re using pm.sendRequest to send your request instead of as a “proper” postman request.

You are going to have to use the response variable from your callback instead of pm.response to get what you want. Take this example of calling the postman echo API:

pm.sendRequest({
    url: 'https://postman-echo.com/post',
    method: 'POST'
}, function(err, res){
    const location = res.headers.find(h => h.key == 'Location');
    pm.environment.set('location', location);
});

So you can see that res is my response variable in the callback. You can get to the headers from there.

Hey @allenheltondev, Thanks for coming back with the solution. It worked and resolved my issue.

Also , is there a way to not send the request if the pre-req script fails for a known reason.

When the prerequest script is running, it’s too late to skip execution.

But something you can do (and I do this in my collection workflows) is if you determine you do not want to run that request, you can programmatically set the request url to something else. So what I do is add this in my prerequest script:

if(someConditionThatPreventsMeFromExecuting){
  pm.request.url = 'https://postman-echo.com/delay/0';
  pm.request.method = 'GET';
  pm.variables.set('skipped', true);
}

Then in the tests tab, I enclose all my tests in an if statement:

const skipped = pm.variables.get('skipped');
if(!skipped){
 // All my tests
}

So the request is still going to execute, but it’s going to hit a dummy endpoint instead of your API.

Hi @allenheltondev, Thanks for the solution.
Also is there a way to read the request header value for a request that is getting sent in the pre-req script.

Yes, if you just use pm.request.headers.get('myHeaderName') you can get access to a specific header in the main request.

1 Like

@allenheltondev I have tried that and its not working for the request that is sent in the pre-req script. It returns “undefined” in the console. Although the header name is correct.

Oh you’re talking about a header in the pm.sendRequest function in the pre-request script?

I am confused. If that’s what you want, you know exactly what those headers are in the request because you defined them. You build the headers, url, method, and body when you use that function.

I might be able to help more if you send me a screenshot of what you have tried and what you expect.

@allenheltondev So in the pre-req, i am hitting three endpoints. First GET request gives me an endpoint in the response header, which becomes the next GET request(Highlighted in red). The request headers for this call are pre populated. I need to extract the “Cookie” from this call, which is used in the main call request header. I tried with “pm.request.headers.get(‘Cookie’)”, but I get undefined in the response(Highlighted in Yellow).
I hope this helps you understand it better.

How are the request headers pre-populated? This is the part that I’m missing.

@allenheltondev The url for second call looks like this.

https://thisIsTheApplicationURL/login/oauth2/code/Chassis?code=8436bfaf-028d-4c55-aa4d-1a6b2a0697d1&scope=openid&iss=https%3A%2F%2Fwam-ist.cloud.bns%3A443%2Fsso%2Foauth2%2Fbns&client_id=test

This url is fetched from the first GET call response. When this url is inputted, it populates the cookies as well, and one of those cookie is populated in the header as value and key “Cookie”. I need to extract the value for this cookie header as shown in the last screenshot.

I hope this helps a little.

@allenheltondev any update on this, buddy ?

Can you post your code? I think that’s the only way I’m going to be able to progress with help from here.

const codeGetRequest = {
url: pm.variables.get(‘test-code-url’),
method: ‘GET’
};

//first get call

pm.sendRequest(codeGetRequest, function (err,res){
console.log(‘Code request sent’);
const location = res.headers.find(h => h.key == ‘Location’);
const locationValue = location.value;
pm.environment.set(‘location’, locationValue);

if(locationValue.includes('response_type')){
    console.log('No Code found. User should sign in.');
}

else{
    var str = locationValue.split("code=")[1];
    var code = str.split("&")[0];
    console.log("CODE is : " + code);
 
    pm.globals.set('jsession_id_url', locationValue);
    pm.globals.set('auth_code', code);
    
    const jSessionIDGetRequest = {
     url: pm.variables.get('jsession_id_url'),
     method: 'GET'
    };

//second GET call(this is the call which has the headers pre populated as the url for this call is extracted from first GET call response)

    pm.sendRequest(jSessionIDGetRequest, function (err,res){
        console.log('JSession ID request sent');
        const cookie = pm.request.headers.get('Cookie');
        console.log('COOKIE : '+cookie);
    });

// POST call

    pm.sendRequest(echoPostRequest, function (err, res) {
    console.log(err ? err : res.json());
    if (err === null) {
        console.log('Saving the token')
        var responseJson = res.json();
    }
});
}

});

const echoPostRequest = {
url: pm.environment.get(“token-url”),
method: ‘POST’,
header: ‘Content-Type:application/x-www-form-urlencoded’,

body: {
mode: ‘urlencoded’,
urlencoded: [
{key: ‘grant_type’, value: ‘authorization_code’, disabled: false},
{key: “code”,value: pm.variables.get(“auth_code”), disabled: false},
{key: “redirect_uri”, value: pm.environment.get(“redirect-uri”), disabled: false},
{key: “client_id”,value: “client_id”, disabled: false},
{key: “client_secret”,value: “secret”, disabled: false},
{key: “user-name-attribute”,value: “sub”, disabled: false},
{key: “provider”,value: “iso”, disabled: false}
]
}
};

@allen.helton this is the pre-req script i am using.
In the second GET call, the following is returning Undefined and that is the only value i am having hard time extracting.
“const cookie = pm.request.headers.get(‘Cookie’);”

I still don’t see where you’re populating headers on that second request. I see that you’re using a variable for the url but your request is pretty explicitly defined without headers:

const jSessionIDGetRequest = {
     url: pm.variables.get('jsession_id_url'),
     method: 'GET'
    };

Either way, pm.request.headers isn’t going to work there. That is for the request object in Postman, not for the request you are sending in this script.

Are you sure the response of that second call doesn’t have the cookie? You could see if it does by using the res variable.

Did we find a solution here? I am facing the same issue @baljindernohra / @allenheltondev