如何使用Request和NodeJS进入重定向页面

时间:2015-01-26 22:03:28

标签: javascript node.js redirect request jsdom

我正在使用Request,Jsdom和NodeJS登录网页。根据{{​​3}},

followRedirect - 将HTTP 3xx响应作为重定向(默认值:true)。此属性也可以实现为将响应对象作为单个参数获取的函数,如果重定向应该继续,则应返回true,否则返回false。

鉴于这是默认的,我认为该请求会给我重定向的页面,而不是中间的重定向页面。

我的代码:

    request(loginPageURL, function(error, response, body) {
    /*Error handling removed for brevity*/
        jsdom.env({
            html: body,
            scripts: [
                'http://code.jquery.com/jquery-1.7.1.min.js'
            ],
            done: function(err, window) {
                //Set login fields  
                var form = $('#authorizationForm');
                var data = form.serialize();
                var url = form.attr('action') || 'get';
                var type = form.attr('enctype') || 'application/x-www-form-urlencoded';
                var method = form.attr('method');

                request({
                    url: url,
                    method: method.toUpperCase(),
                    body: data,
                    headers: {
                        'Content-type': type
                    }
                }, function(error, response, body) {
                    if (!error) {
                        console.log("Response.statusCode:" + response.statusCode);
                        console.log("Body:" + body);

登录后不是给我主页,而是输出:

Response.statusCode: 302
Body: To access this site, go to <a href="...">

虽然从重定向页面获取代码可能很有用,但如何跳转到将其重定向到的页面?

1 个答案:

答案 0 :(得分:1)

这是非GET请求吗?然后,您需要明确设置followAllRedirects: true

  

followAllRedirects - 将非GET HTTP 3xx响应作为重定向(默认值:false

https://github.com/request/request

followRedirect的文档令人困惑,因为它们似乎并不表示followRedirect仅适用于GET。)