Accessing Request Values from the Console

Hello,

I have a pre-request script written in Postman. One of the calls redirects you to a different url as part of the url and I am wanting to access this url. I can see it in the console, but I have no idea how to access it in the script itself. You can see two gray urls, the first is the “codeRequest” that is the request that is being sent and the second is the url that it is redirected to after a successful request. Basically, I want to get the code value out of the second gray url. How can I access this value/url?

hi @aviation-explorer-21

Is it returned in the response header as a redirect or anything like that?
If you can grab it from the response header you could do something like:

let redirectUrl = pm.response.headers.get('Location'); // Change to actual header key
pm.environment.set('YourRedirectVariable', redirectUrl);

I unfortunately tried that but when I try to get the headers out of the response, it is just the response of the API that I initially called and it has no info about the redirect URL that I want. What you suggested is exactly what I want to do though!

Go to settings (within your API call - next to test tab), turn off automatically follow redirects…

Then something like this should work:

//Get all headers
var responseHeaders = pm.response.headers;
console.log(responseHeaders);

//Get specific header value - based on key name
var headerValue = responseHeaders.get("location");
console.log(headerValue);

I tried this just on a redirect and it gives me the URL I was looking for…

Hope it helps.

Yes this does work if you are doing a regular postman API call, but I was doing everything in a collection level pre-request script to grab authorization from our authorization server automatically instead of having to put the authorization API calls into a folder and manually running the folder each time. However, since I couldn’t find a solution to grabbing the redirect URL in the pre-request script, I have to run the scripts manually. I just wish there was a way to run the folder in the pre-request script.

Ah, I didn’t realise it was from a prereq.

You could try setting ‘followRedirects: false’ as a request option.
I didn’t have much luck on my own test, but from what I read it ‘sometimes’ works depending on the config of the API.

Alternatively, could you use the OAuth 2.0 option within the Auth tab?

All of the information you are feeding in to your prereq script could be input here (at collection level) instead.

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