Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple 'Cookie' headers in a node.js request

I've seen how to make a request with a single cookie, and I've seen how to write a response with multiple cookies, but does anyone know how to write a request in node.js using http module (if possible) with multiple 'Cookie' headers?

So far the only ways I've seen to make a request in node.js involve passing an object as the parameter to a function, which would require having two identical keys.

headers = {
    Cookie: firstCookie,
    Cookie: secondCookie
}

so wouldn't work.

This is a node.js question, but I'm not extremely confident with http, so I'm not sure if there isn't a way to set two distinct cookies in header. Is it possible to concatenate the two into a single header? Would a request with two separately defined cookies vary from one with a single header containing both?

like image 712
twinlakes Avatar asked Aug 27 '13 02:08

twinlakes


1 Answers

The 'Cookie' property you added is a direct header in your HTTP request. You should use only one 'Cookie' header and encode your cookies properly to one valid cookie header string, like that:

var headers = {
    Cookie: 'key1=value1; key2=value2'
}

Also, instead of using nodeJS native HTTP client which usually will make you write lots of boilerplate code, I would recommend you to use a much simplified library like Requestify..

This is how you can make an HTTP request with cookies using requestify:

var requestify = require('requestify');

requestify.get('http://example.com/api/resource', {
    cookies: {
        'key1': 'val1',
        'key2': 'val2',    
    }
})
  .then(function(response) {
      // Get the response body (JSON parsed or jQuery object for XMLs)
      response.getBody();
  }
);
like image 123
ranm8 Avatar answered Oct 21 '22 19:10

ranm8