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);
});
}
});
First, I do a POST, which gives a respone.statusCode == 302. The body is empty. I expected the body to contain the redirected page.
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.
Anyone know of how to go about this?
Drop-in replacement for Node's http and https modules that automatically follows redirects. follow-redirects provides request and get methods that behave identically to those found on the native http and https modules, with the exception that they will seamlessly follow redirects.
redirect() function, we can now discuss how to redirect back to original URL in NodeJS. Back redirect: We can use this method to redirects the request back to the referrer. If no referrer is present, the request is redirected to “/” route by default.
To follow redirect with Curl, use the -L or --location command-line option. This flag tells Curl to resend the request to the new address. When you send a POST request, and the server responds with one of the codes 301, 302, or 303, Curl will make the subsequent request using the GET method.
The HTTP 200 OK success status response code indicates that the request has succeeded. A 200 response is cacheable by default. The meaning of a success depends on the HTTP request method: GET : The resource has been fetched and is transmitted in the message body.
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
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);
});
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With