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

6

25
function getCookies(){

    request('http://google.com', function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(response.headers);
        }
    })
}

Result

{ date: 'Fri, 11 Dec 2015 07:15:50 GMT',
  expires: '-1',
  'cache-control': 'private, max-age=0',
  'content-type': 'text/html; charset=EUC-KR',
  p3p: 'CP="This is not a P3P policy! See https://www.google.com/support/accounts/answer/151657?hl=en for more info."',
  server: 'gws',
  'x-xss-protection': '1; mode=block',
  'x-frame-options': 'SAMEORIGIN',
  'set-cookie': 
   [ 'PREF=ID=1111111111111111:FF=0:TM=1449818150:LM=1449818150:V=1:S=Q3BB20FA6TkaZymd; expires=Thu, 31-Dec-2015 16:02:17 GMT; path=/; domain=.google.co.kr',
     'NID=74=hnriWxk7N9jHtP5W0qgaxrwD1YuNKOmJg748ucxWilu9jaqHJVovfkYdvMr0tlp-VToID5cdTNDSXNXqr4M8umJ9traab67x2xZKfu3hJbsBRXeVvyiCOcwZ8bkXNcU4; expires=Sat, 11-Jun-2016 07:15:50 GMT; path=/; domain=.google.co.kr; HttpOnly' ],
  'accept-ranges': 'none',
  vary: 'Accept-Encoding',
  connection: 'close' }

I want to pick up value of 'set-cookie' from response headers. How to pick it up? Is there any cool and simple way? Should I use for statement from filedkey, or. What should I do? I don't know I'm totally newbie on Javascript. Thanks...

Voyeur answered 11/12, 2015 at 7:24 Comment(0)
U
18
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)
})
Unlisted answered 11/12, 2015 at 7:27 Comment(1)
wow, really? this is a much less friendly way to get cookies compared to express on the server side where i can just say "req.cookies.cookieName"Bodily
O
12

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
Oxalis answered 9/3, 2017 at 4:24 Comment(0)
W
8

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).

Waltz answered 11/12, 2015 at 7:38 Comment(0)
S
2

If you don't care what's in the cookie and you just want to use it, try this clean approach:

var request = require('request');
var j = request.jar();
var request = request.defaults({jar:j});
request('http://www.google.com', function () {
  request('http://images.google.com', function (error, response, body){
     // this request will will have the cookie which first request received
     // do stuff
  });
});
Somatotype answered 7/9, 2018 at 11:29 Comment(1)
This is very simple and neat solution!Stacy
P
1

When you import request module, probably you did it like this

var request = require('request');

Add one line as follows

var request = require('request');
var request = request.defaults({jar: true})

And just use request module as usual. You can get the set cookie response.

Pyretic answered 26/12, 2019 at 12:1 Comment(0)
M
0

Try doing this:

npm install tough-cookie

const request = require("request");
const tough = require('tough-cookie');
const  Cookie = tough.Cookie;

request.get(options, (error, response, body) => {
        const cookie = Cookie.parse(response.headers['set-cookie'][0]);
        console.log(cookie.cookieString());
});
Masakomasan answered 2/3, 2019 at 22:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.