How do I get the redirected url from the nodejs request module?

There are two very easy ways to get hold of the last url in a chain of redirects.

var r = request(url, function (e, response) {
  r.uri
  response.request.uri
})

The uri is a object. uri.href contains the url, with query parameters, as a string.

The code comes from a comment on a github issue by request’s creator: https://github.com/mikeal/request/pull/220#issuecomment-5012579

Example:

var request = require('request');
var r = request.get('http://google.com?q=foo', function (err, res, body) {
  console.log(r.uri.href);
  console.log(res.request.uri.href);

  // Mikael doesn't mention getting the uri using 'this' so maybe it's best to avoid it
  // please add a comment if you know why this might be bad
  console.log(this.uri.href);
});

This will print http://www.google.com/?q=foo three times (note that we were redirected to an address with www from one without).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)