Upload
jay-dihenkar
View
4.401
Download
1
Embed Size (px)
Citation preview
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
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
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.