使用 node.js 请求进行重定向 [英] Follow redirect with node.js request

查看:71
本文介绍了使用 node.js 请求进行重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习 node.js,并且我正在开发一个实用程序来登录站点,然后提取一些信息.我在文档中读到重定向应该自动工作",但我无法让它工作.

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

首先,我做了一个 POST,它给出了一个 respone.statusCode == 302.正文是空的.我希望正文包含重定向的页面.

First, I do a POST, which gives a respone.statusCode == 302. The body is empty. I expected the body to contain the redirected page.

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

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.

有人知道怎么做吗?

推荐答案

默认情况下,重定向仅针对 GET 请求打开.要跟踪 POST 中的重定向,请将以下内容添加到您的配置中:

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

更新代码:

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

这篇关于使用 node.js 请求进行重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆