简体   繁体   中英

How do I send HTTP request with cookie by NodeJS?

I want to send a HTTP POST request with cookie by NodeJS, to simulate the behavior of the following "curl" command:

[Notice: here is HTTPS not 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/

My current code like following, but I always get 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);
        }
    });

You get 403 error, not because of cookie header but a missing content-type header. Modify your headers field as in this way.

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

Also add a content-length header for the length of your post payload.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM