0

I need to get the url of the response (after any redirects) from a request made in the Pre-request Script. Is this possible in postman?

The postman response object doesn't seem to include the url https://learning.postman.com/docs/writing-scripts/script-references/postman-sandbox-api-reference/#scripting-with-response-data

This doesn't work, but I was hoping to do something like:

pm.sendRequest("https://foobar.com", function (err, response) {
    console.log(response.url);
});
Liam Bell
  • 55
  • 1
  • 8

2 Answers2

1

I found a solution by disabling the Automatically follow redirects setting, then checking response.headers for a location header e.g.

const initialUrl = "https://foobar.com";

pm.sendRequest(initialUrl, function (err, response) {
    getLocationAfterRedirects(response, initialUrl).then((url) => setToken(url));
});

function getLocationAfterRedirects(response, requestUrl) {
    return new Promise((resolve) => {

        if (!isResponseRedirect(response)) {
            return resolve(requestUrl);
        }

        const redirectUrl = response.headers.find(h => h["key"] === "Location")["value"];

        pm.sendRequest(redirectUrl, (err, res) => {
            getLocationAfterRedirects(res, redirectUrl)
                .then((location) => resolve(location));
        });

    });
}

function isResponseRedirect(response) {
    return response.code > 300 && response.code < 400;
}
Liam Bell
  • 55
  • 1
  • 8
0

Try pm.request.headers["referer"].

After you make the request, the redirect url will be in the temporary request headers.

You can refer to this Twitter post for more information: https://twitter.com/ambertests/status/1153709610768859136

Hope this helps.

Community
  • 1
  • 1