【问题标题】:Follow redirect with node.js request使用 node.js 请求跟随重定向
【发布时间】:2015-12-09 00:06:31
【问题描述】:

我正在尝试学习 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,它给出了一个 respon.statusCode == 302。正文是空的。我希望正文包含重定向的页面。

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

有人知道怎么做吗?

【问题讨论】:

  • action="login" 这是什么意思?你的文件名是什么?
  • 这只是服务器期望的一些表单数据。
  • 是的。扩展名是否正确?
  • 这不是文件参考。布兰登·史密斯发现了严重的问题。还是谢谢!

标签: javascript node.js http request


【解决方案1】:

默认情况下,仅对 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!
  • 这似乎不适用于request-promise -- 我的.then() 块永远不会触发。
  • 只是为了超级清楚-“配置”是指过去请求的选项对象?还有其他可以更改的配置吗?
  • 正确,你传递给请求的对象。见第 4 行。
猜你喜欢
  • 2017-01-24
  • 2016-08-30
  • 2012-01-04
  • 2021-08-27
  • 2017-09-10
  • 1970-01-01
  • 2019-01-18
  • 2012-06-19
  • 2023-03-25
相关资源
最近更新 更多