Rohit Kumar
Rohit Kumar

Reputation: 446

Create cookie by javascript and read it from Node.js

I am developing a website in which i want to create a cookie from JavaScript and read it's value from Node.js server.

Please give some code..

Upvotes: 0

Views: 35

Answers (1)

Vivek Pratap Singh
Vivek Pratap Singh

Reputation: 9974

With JavaScript, a cookie can be created like this:

document.cookie = "username=Vivek Singh";

With NodeJs, Below code could help since there is no quick function to access cookies,

var getCookies = function(request) {
  var cookies = {};
  request.headers && request.headers.cookie.split(';').forEach(function(cookie) {
    var parts = cookie.match(/(.*?)=(.*)$/)
    cookies[ parts[1].trim() ] = (parts[2] || '').trim();
  });
  return cookies;
};

Then, to get a specific cookie simply call this method:

getCookies (request)['username']

Upvotes: 2

Related Questions