如何通过NodeJS发送带有cookie的HTTP请求?

时间:2015-12-09 21:09:09

标签: javascript node.js http cookies web-development-server

我想通过NodeJS发送带有cookie的HTTP POST请求, 模拟以下行为" 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);
        }
    });

1 个答案:

答案 0 :(得分:1)

您收到403错误,不是因为Cookie标头而是缺少内容类型标头。 以这种方式修改标题字段。

    "headers": {
        "Referer": endpoint + "accounts/login/",
        "Cookie": "csrftoken=" + csrftoken,
        'Content-Type': 'application/x-www-form-urlencoded'
    },

还为帖子有效负载的长度添加内容长度标头。