使用 Node.js request 跟随重定向

12

我正在尝试学习node.js,并且正在开发一个用于登录网站并提取一些信息的实用工具。在文档中,我读到重定向应该会"自动工作",但我无法使其正常工作。

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

首先,我进行POST操作,得到了response.statusCode == 302的响应。但是,正文为空。我预期正文中会包含被重定向的页面。

然后我在response.headers['location']中找到了“新”的url。使用该url时,正文只包含一个“未登录”页面,而不是我预期的页面。

有人知道如何解决这个问题吗?


action = "login" 这是什么意思?你的文件名是什么? - I-Kod
那只是服务器期望的一些表单数据。 - kaze
是的。扩展名正确吗? - I-Kod
这不是文件引用。Brandon Smith 找到了实际的问题。无论如何感谢你! - kaze
1个回答

33

默认情况下,重定向仅适用于 GET 请求。如果要在POST请求中跟随重定向,请将以下内容添加到您的配置文件中:

followAllRedirects: true

更新后的代码:

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

太棒了!使用 followAllRedirects 第一次尝试就成功了! - kaze
1
这似乎不能与 request-promise 一起使用 - 我的 .then() 块从未触发。 - chovy
只是为了非常清楚 - 你所说的“config”是指传递给请求的选项对象吗?还有其他可以更改的配置吗? - Vincent Buscarello
正确,您传递给请求的对象。请参见第4行。 - Brandon Smith

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接