Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to follow through on a url that redirects me to another page using the nodejs request module.

Combing through the docs I could not find anything that allows me to retrieve the url after the redirect.

My code is as follows:

var request = require("request"),     options = {       uri: 'http://www.someredirect.com/somepage.asp',       timeout: 2000,       followAllRedirects: true     };  request( options, function(error, response, body) {      console.log( response );  }); 
like image 647
hitautodestruct Avatar asked May 22 '13 08:05

hitautodestruct


People also ask

How do you get a redirected URL?

Click the URL Redirects tab. In the upper right, click Add URL redirect. In the right panel, select the Standard or Flexible redirect type. A standard redirect is used to redirect one URL to another.

How do I find the URL of a node JS?

If you want to get the path info from request urlvar url_parts = url. parse(req. url); console. log(url_parts); console.

How do I redirect a path in node JS?

nodejs1min read In express, we can use the res. redirect() method to redirect a user to the different route. The res. redirect() method takes the path as an argument and redirects the user to that specified path.

Does node fetch follow redirects?

Manual RedirectThe redirect: 'manual' option for node-fetch is different from the browser & specification, which results in an opaque-redirect filtered response. node-fetch gives you the typical basic filtered response instead.


1 Answers

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).

like image 172
gabrielf Avatar answered Oct 19 '22 15:10

gabrielf