4
In NodeJS http library has Access to the Header Component and Hence it can also access Cookies. Reading Cookies from HTTP Headers and Writing our own cookies parsing function is most reliable than using currently existing Cookies related node packages. var http = require('http' ); The http has access to the request and response objects of the HTTP request. From the request object we can read the already set cookies and other headers, while we can write the response headers to instruct the browsers to manipulate the cookies. The entire existing (already set) cookies are stored in the request.headers.cookie . The cookies we recieve is as follows : cookie1=val1; cookie2=val2 NodeJS Working with Cookies 1. Introduction 2. Reading and Parsing Cookies 2.1 Require http 2.2 Parsing Cookies

Working with Cookies in NodeJS

Embed Size (px)

Citation preview

Page 1: Working with Cookies in NodeJS

InNodeJShttplibraryhasAccesstotheHeaderComponentandHenceitcanalsoaccessCookies.

ReadingCookiesfromHTTPHeadersandWritingourowncookiesparsingfunctionismostreliablethanusingcurrentlyexistingCookiesrelatednodepackages.

varhttp=require('http');

ThehttphasaccesstotherequestandresponseobjectsoftheHTTPrequest.

Fromtherequestobjectwecanreadthealreadysetcookiesandotherheaders,whilewecanwritetheresponseheaderstoinstructthebrowserstomanipulatethecookies.

Theentireexisting(alreadyset)cookiesarestoredintherequest.headers.cookie.

Thecookieswerecieveisasfollows:

cookie1=val1;cookie2=val2

NodeJSWorkingwithCookies1.Introduction

2.ReadingandParsingCookies

2.1Requirehttp

2.2ParsingCookies

Page 2: Working with Cookies in NodeJS

Nowlet'stryparsingthecookiestringtoJSON:

Steps:

1. TrimtheCookieStringtogetKey-Valuepairbysplit(';')2. TrimtheCookiebysplit('=')3. WriteeachKey-ValuepairtoJSON

ParseFunction:

functionparseCookies(request){varlist={},rc=request.headers.cookie;rc&&rc.split(';').forEach(function(cookie){varparts=cookie.split('=');list[parts.shift().trim()]=decodeURI(parts.join('='));});returnlist;}

Thisparsefunctionwillenablereadcookiesflawlessly.

WecaneasilysetthecookiesorupdateexistingvaluesbyusingsetHeader()function.

Functiontosetcookies:

response.setHeader('Set-Cookie',+['cookie1='+valcookie1,+'cookie2'+valcookie2+]);

NOTE:ifweoverwritetheSet-Cookie,thepreviousvaluewillbelost,henceweneedtoreadandappendallcookiesatthesametime.

Toovercomethisissue,wecangettheheadercookiestringreq.headers.cookieandappendtheupdatedcookiestothetrailingpartoftheCookiestring.

2.3SettingorUpdatingCookies

Page 3: Working with Cookies in NodeJS

FindthefollowingcodesnippettoSet-Updatecookiesusingthemethodasdiscussedabove:

varhttp=require('http');functionparseCookies(request){varlist={},rc=request.headers.cookie;rc&&rc.split(';').forEach(function(cookie){varparts=cookie.split('=');list[parts.shift().trim()]=decodeURI(parts.join('='));});returnlist;}http.createServer(function(request,response){//ToReadaCookievarcookies=parseCookies(request);console.log('JSON='+JSON.stringify(cookies));setCookies=[];if(cookies!={}){console.log(cookies.count+"\n");varcount=parseInt(cookies.count);count=count+1;setCookies.push("count="+count);}else{varcount=0;vardummy="something";setCookies.push("count="+count);setCookies.push("dummy+"+dummy);}//ToWriteaCookieresponse.setHeader("Set-Cookie",setCookies);console.log(response.headers.cookie);response.end('HelloWorld\nTheCountis'+count);}).listen(3000);console.log('Serverrunningathttp://localhost:3000/');

2.4SampleCookieSet-Update.

Page 4: Working with Cookies in NodeJS