user2085143 user2085143 - 2 months ago 18
Node.js Question

Get Response URL from GET Request

Using the request node library to make GET requests and and wondering how to grab the URL from the response returned.

Something like

var request = require('request');
request('http://www.somewebsite.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // grab the url here
}
})


assuming the response returned is not www.somewebsite.com but a redirect.

Answer

Start at the documentation. Search it for redirect and you'll find:

followRedirect - follow HTTP 3xx responses as redirects (default: true). This property can also be implemented as function which gets response object as a single argument and should return true if redirects should continue or false otherwise.

Note the status code. You only get the 200 after the redirect has been followed.

Therefore:

var request = require('request');
request({
        uri: 'http://google.com',
        followRedirect: function(response) {
            console.log("Redirecting to " + response.headers.location);
            return true;
        }
    },
    function(error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(body)
        }
    }
);