postmanpostman-pre-request-script

Get response url from Postman Pre-Request Script


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);
});

Solution

  • 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;
    }