问题描述
我正在尝试学习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请求进行重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!