我希望通过NodeJS发送带有cookie的HTTP请求,以模拟以下"curl“命令的行为:
注意:这里是HTTPS而不是HTTP
curl -v --header "Referer: https://some-domain.com/accounts/login/" --cookie csrftoken=xxxxxssometokenxxxxx --data 'csrfmiddlewaretoken=xxxxxssometokenxxxxx&username=tom.rock&password=somepassword' https://some-domain.com/我的当前代码如下所示,但我总是得到403
var request = require("request");
var querystring = require('querystring');
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';
var endpoint = "https://some-domain.com/";
var username = "tom.rock";
var password = "somepassword";
var csrftoken = "xxxxxssometokenxxxxx"; // Guarantee the token is fresh
var form = {
username: username,
password: password,
csrfmiddlewaretoken: csrftoken
};
request({
"headers": {
"Referer": endpoint + "accounts/login/",
"Cookie": "csrftoken=" + csrftoken
},
"url": endpoint,
"body": querystring.stringify(form),
"method": "POST"
}, function(error, response, body) {
if (error) {
console.log("Here is error:");
console.dir(error);
} else {
console.log("Status code is " + response.statusCode);
}
});发布于 2015-12-09 23:18:28
您得到403错误,不是因为cookie标题,而是因为缺少内容类型的标题。按照这种方式修改标头字段。
"headers": {
"Referer": endpoint + "accounts/login/",
"Cookie": "csrftoken=" + csrftoken,
'Content-Type': 'application/x-www-form-urlencoded'
},还为post负载的长度添加一个内容长度标题。
https://stackoverflow.com/questions/34189019
复制相似问题