Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

node.js - 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 );

});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...