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

How do I send HTTP request with cookie by NodeJS?

我想通过 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);
        }
    });

您收到 403 错误,不是因为 cookie header,而是缺少 content-type header。 按照这种方式修改您的 headers 字段。

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

另外添加 content-length header 作为 post 负载的长度。