newspaint

Documenting Problems That Were Difficult To Find The Answer To

How To Get Cookies From Node.JS HTTP Response

So you make a HTTP request using the http library and you want the cookies returned by the remote webserver (maybe for a later request, a session cookie for example)?

The approach I ended up taking in Node.JS was to inspect the response.headers[“set-cookie”] field which is set to an array of cookies if they have been given in the server response.

e.g.

var http = require( "http" );
var url = require( "url" );

var urlstring = "http://www.voa.com/";
var parsedurl = url.parse( urlstring );
var options = {
  hostname: parsedurl.hostname,
  port: ( parsedurl.port || 80 ), // 80 by default
  method: 'GET',
  path: parsedurl.path,
  headers: { },
};

var request = http.request(
  options,
  function ( response ) {
    // display returned cookies in header
    var setcookie = response.headers["set-cookie"];
    if ( setcookie ) {
      setcookie.forEach(
        function ( cookiestr ) {
          console.log( "COOKIE:" + cookiestr );
        }
      );
    }

    var data = "";
    response.on(
      "data",
      function ( chunk ) { data += chunk; }
    );

    response.on(
      "end",
      function () {
        console.log( "STATUS:" + response.statusCode );
        console.log( "  DATA:" + data );
      }
    );
  }
);

request.on(
  "error",
  function( err ) {
    console.error( "ERROR:" + err );
  }
);

request.end(); // let request know it is finished sending

This will output cookie information like:

COOKIE:JSESSIONID=7bcc3a128; Path=/

If you want to send cookies with your request add a header to the options you pass the request, e.g.:

var cookies = [
  "JSESSIONID=c2aa6fa21",
  "site_ip=10.18.32.12",
];

options.headers["Cookie"] = cookies.join( "; " );

5 responses to “How To Get Cookies From Node.JS HTTP Response

  1. lantern November 9, 2015 at 10:11 am

    Thank you very much!

  2. Viktor February 29, 2016 at 9:54 am

    Thank you very much, you saved my bacon.

  3. Cat January 12, 2017 at 4:34 pm

    Where did “site_ip=10.18.32.12” come from?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: