【问题标题】:How do I send HTTP request with cookie by NodeJS?如何通过 NodeJS 发送带有 cookie 的 HTTP 请求?
【发布时间】:2016-03-15 07:53:25
【问题描述】:

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

【问题讨论】:

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


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-03
    • 2019-11-06
    • 2013-01-15
    相关资源
    最近更新 更多