简体   繁体   English

遵循node.js请求的重定向

[英]Follow redirect with node.js request

I'm trying to learn node.js, and I'm working on a utility to log in on a site, and then exctract some info. 我正在尝试学习node.js,我正在研究一个实用程序来登录一个站点,然后提取一些信息。 I have read that redirects should "work automatically" in the documentation, but I can't get it to work. 我已经读过重定向应该在文档中“自动工作”,但是我无法让它工作。

request({
    url: start_url,
    method: 'POST',
    jar: true,
    form: {
        action: 'login',
        usertype: '2',
        ssusername: '****',
        sspassword: '****',
        button: 'Logga in'
    }
}, function(error, response, body) {
    if (error) {
        console.log(error);
    } else {
        console.log(body, response.statusCode);
        request(response.headers['location'], function(error, response, html) {
            console.log(html);
        });
    }
});

First, I do a POST, which gives a respone.statusCode == 302. The body is empty. 首先,我做一个POST,它给出了一个respone.statusCode == 302.正文是空的。 I expected the body to contain the redirected page. 我希望正文包含重定向的页面。

Then I found the "new" url, in response.headers['location']. 然后我在response.headers ['location']找到了“新”网址。 When using that, the body just contains a "not logged in" page, instead of the page I was expecting. 使用它时,正文只包含一个“未登录”页面,而不是我期望的页面。

Anyone know of how to go about this? 有谁知道如何去做?

Redirects are turned on by default for GET requests only. 默认情况下,仅对GET请求启用重定向。 To follow the redirects in your POST , add the following to your config: 要在POST中关注重定向,请将以下内容添加到配置中:

followAllRedirects: true

Updated Code: 更新的代码:

request({
    url: start_url,
    method: 'POST',
    followAllRedirects: true,
    jar: true,
    form: {
        action: 'login',
        usertype: '2',
        ssusername: '****',
        sspassword: '****',
        button: 'Logga in'
    }
}, function(error, response, body) {
    if (error) {
        console.log(error);
    } else {
        console.log(body, response.statusCode);
        request(response.headers['location'], function(error, response, html) {
            console.log(html);
        });
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM