Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - 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. 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. I expected the body to contain the redirected page.

Then I found the "new" url, in 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?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Redirects are turned on by default for GET requests only. To follow the redirects in your POST, add the following to your config:

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);
        });
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...