views:

337

answers:

2

I want to be able to set a single cookie, and read that single cookie with each request made to the nodejs server instance. Can it be done in a few lines of code, without the need to pull in a third party lib?

var http = require('http');

http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello World\n');
}).listen(8124);

console.log('Server running at http://127.0.0.1:8124/');

Just trying to take the above code directly from nodejs.org, and work a cookie into it.

+1  A: 

Cookies are transfered through HTTP-Headers
You'll only have to parse the request-headers and put response-headers.

Tobias P.
+5  A: 

There is no quick function access to getting/setting cookies, so I came up with the following hack:

var http = require('http');

http.createServer(function (request, response) {
  // To Get a Cookie
  var cookies = {};
  request.headers.cookie.split(';').forEach(function( cookie ) {
    var parts = cookie.split('=');
    cookies[ parts[ 0 ].trim() ] = ( parts[ 1 ] || '' ).trim();
  });

  // To Write a Cookie
  response.writeHead(200, {
    'Set-Cookie': 'mycookie=test',
    'Content-Type': 'text/plain'
  });
  response.end('Hello World\n');
}).listen(8124);

console.log('Server running at http://127.0.0.1:8124/');

This will store all cookies into the cookies object, and you need to set cookies when you write the head.

Corey Hart