How to get cookies from request module in node.js?

Generally speaking with Node, if it's a common problem to solve, someone's already gone to the trouble to write and publish something on npm.

For example, request-cookies!

In particular, I think you'll find the toJSON() method most helpful, though admittedly the package's documentation is rather light. You can check out the tests for some working examples.

That said, request already has some extensive documentation on cookies as well - you might find this suits your needs:

Cookies are disabled by default (else, they would be used in subsequent requests). To enable cookies, set jar to true (either in defaults or options).

(Scroll down to the bottom of the readme to find the bits about cookies).


function getCookies(callback){

    request('http://google.com', function (error, response, body) {
        if (!error && response.statusCode == 200) {
            return callback(null, response.headers['set-cookie']);
        } else {
            return callback(error);
        }
    })
}

then you can call:

getCookies(function(err, res){
    if(!err)
       console.log(res)
})

Here is how you can use request-cookies as @brandonscript said.

var request = require('request');
var Cookie = require('request-cookies').Cookie;

request.get('https://google.com', function(err, response, body) {
  var rawcookies = response.headers['set-cookie'];
  for (var i in rawcookies) {
    var cookie = new Cookie(rawcookies[i]);
    console.log(cookie.key, cookie.value, cookie.expires);
  }
});

Sample output from google:

NID 98=FfYHDY9-40JzE78qxIpaMugODJ4y4zJIydluKUffvh1lDs70DYk7vrlmw2ca2gD54ywx5WV44Utz9EdLOdFE6IcW2BUGfiVpHZx3kWh69tT_eWlXZTiFkRo7TVr_9WWH 2017-09-08T04:22:41.000Z