Kilian
Kilian

Reputation: 2282

Authenticate via POST request in Node.js

I'm trying to authenticate with a site through node by sending my username and password through a POST request, as that's how the login form seems to be doing it. When trying it out with Postman it works just fine and I'm redirected to the my dashboard.

Username and password fields are unfortunately not labeled as username and password, but as j_username and j_password.

This is the data Postman shows me (for reference):

POST /path/for/auth/request HTTP/1.1
Host: site.com
Cache-Control: no-cache
Postman-Token: b6656210-caeb-2b62-d6b6-e10e642b200b
Content-Type: application/x-www-form-urlencoded
j_username=myusername&j_password=mypassword

So I try this in node:

var request = require('request');
request.post({
    headers: {'content-type' : 'application/x-www-form-urlencoded'},
    url:     'https://site.com/path/for/auth/request',
    body:    "j_username=myusername&j_password=mypassword"
}, function(err, res, body){
    console.log(body);
});

But unfortunately it's coming back empty and err is set to null.

What could be going wrong here? Or is there a better way of authenticating with this resource? As far as I can tell Basic Auth through a header isn't possible here.

Thanks.

Upvotes: 0

Views: 600

Answers (1)

Peter Lyons
Peter Lyons

Reputation: 145994

The site is probably sending you an HTTP 302 redirect, so that's considered success, which is why there's no error, but there's also no response body, which is why it's "empty". You'll want to look at the statusCode as well as the Location header in the response.

Upvotes: 2

Related Questions