Authenticate via POST request in Node.js

為{幸葍}努か 提交于 2021-01-29 11:08:20

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/24922387/authenticate-via-post-request-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!