Как получить перенаправленный url из модуля requestjs request?
Я пытаюсь пройти через URL-адрес, который перенаправляет меня на другую страницу, используя модуль request_s .
С помощью docs я не смог найти ничего, что позволило бы мне получить URL-адрес после перенаправления.
Мой код выглядит следующим образом:
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 );
});
Ответы
Ответ 1
Есть два очень простых способа заполучить последний URL-адрес в цепочке перенаправления.
var r = request(url, function (e, response) {
r.uri
response.request.uri
})
Ури - это объект. uri.href содержит URL-адрес с параметрами запроса в виде строки.
Код исходит из комментария к проблеме github по запросу создателя: 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 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 из одного без).
Ответ 2
Чтобы найти URL-адрес перенаправления, попробуйте следующее:
var url = 'http://www.google.com';
request({ url: url, followRedirect: false }, function (err, res, body) {
console.log(res.headers.location);
});
Ответ 3
request
получает перенаправления по умолчанию, он может получить по 10 переадресаций по умолчанию. Вы можете проверить это в docs. Недостатком этого является то, что вы не знаете, является ли URL-адрес перенаправленным или оригинальным по умолчанию.
Например:
request('http://www.google.com', function (error, response, body) {
console.log(response.headers)
console.log(body) // Print the google web page.
})
выводит вывод
> { date: 'Wed, 22 May 2013 15:11:58 GMT',
expires: '-1',
'cache-control': 'private, max-age=0',
'content-type': 'text/html; charset=ISO-8859-1',
server: 'gws',
'x-xss-protection': '1; mode=block',
'x-frame-options': 'SAMEORIGIN',
'transfer-encoding': 'chunked' }
но если вы укажете опцию followRedirect
как false
request({url:'http://www.google.com',followRedirect :false}, function (error, response, body) {
console.log(response.headers)
console.log(body)
});
он дает
> { location: 'http://www.google.co.in/',
'cache-control': 'private',
'content-type': 'text/html; charset=UTF-8',
date: 'Wed, 22 May 2013 15:12:27 GMT',
server: 'gws',
'content-length': '221',
'x-xss-protection': '1; mode=block',
'x-frame-options': 'SAMEORIGIN' }
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="http://www.google.co.in/">here</A>.
</BODY></HTML>
Так что не беспокойтесь о получении перенаправленного контента. Но если вы хотите узнать, перенаправлено ли оно или нет, установите followRedirect
false и проверьте заголовок location
в ответе.
Ответ 4
Вы можете использовать форму функции для followRedirects
, например:
options.followRedirects = function(response) {
var url = require('url');
var from = response.request.href;
var to = url.resolve(response.headers.location, response.request.href);
return true;
};
request(options, function(error, response, body) {
// normal code
});