如何从nodejs请求模块获取重定向的URL? [英] How do I get the redirected url from the nodejs request module?
问题描述
我正在尝试使用url将我使用nodejs 请求模块.
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.
我的代码如下:
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 );
});
推荐答案
有两种非常简单的方法来获取重定向链中的最后一个URL.
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
})
uri是一个对象. uri.href包含带有查询参数的URL作为字符串.
The uri is a object. uri.href contains the url, with query parameters, as a string.
代码来自请求创建者对github问题的评论: https://github.com /mikeal/request/pull/220#issuecomment-5012579
The code comes from a comment on a github issue by request's creator: https://github.com/mikeal/request/pull/220#issuecomment-5012579
示例:
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);
});
这将打印 http://www.google.com/?q=foo 三次(请注意,我们从一个没有www的地址重定向到了带有www的地址.
This will print http://www.google.com/?q=foo three times (note that we were redirected to an address with www from one without).
这篇关于如何从nodejs请求模块获取重定向的URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!