Javascript 使用 node.js 请求进行重定向
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32540232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Follow redirect with node.js request
提问by kaze
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.
我正在尝试学习 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);
});
}
});
First, I do a POST, which gives a respone.statusCode == 302. The body is empty. I expected the body to contain the redirected page.
首先,我做了一个 POST,它给出了一个 respone.statusCode == 302。正文是空的。我希望正文包含重定向的页面。
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.
然后我在 response.headers['location'] 中找到了“新”网址。使用它时,正文只包含一个“未登录”页面,而不是我期望的页面。
Anyone know of how to go about this?
有谁知道如何解决这个问题?
回答by Brandon Smith
Redirects are turned on by default for GETrequests only. To follow the redirects in your POST, add the following to your config:
默认情况下,仅为GET请求启用重定向。要遵循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);
});
}
});