Node.js cookie-parser returns encoded characters

2k Views Asked by At

I'm using cookie-parser for giving user a signed cookie, but I have problems with decoding them manually. Server returns cookies with hidden hex codes (I guess?). Example:

app.use(cookieParser('bar'));
...
res.cookie('nickname', 'foo', { signed: true });

Then I have a cookie with weird %3A characters nickname=s%3Afoo.FHkzIYqqvAuLEKKzpcNGhMjZQ0G88QpHNtxycPd0GFE and I can't decode it

cookieParser.signedCookie('s%3Afoo.FHkzIYqqvAuLEKKzpcNGhMjZQ0G88QpHNtxycPd0GFE', 'bar')

returns the same string. When I change %3A to : (hex encode?) like

cookieParser.signedCookie('s:foo.FHkzIYqqvAuLEKKzpcNGhMjZQ0G88QpHNtxycPd0GFE', 'bar')

I got foo - the correct value. Does anyone know how to handle it automatically? Thank you very much for your help.

1

There are 1 best solutions below

0
On BEST ANSWER

The string you are getting back is urlencoded ( RFC 3986 ) which means that you need to decode it before you can work with it normally. ( Note: Wikipedia has this listed as 'Percent Encoding' )

The decode command in JavaScript is unescape however as of JavaScript 1.5, this command is deprecated and you should use decodeURI or decodeURIComponent instead.

The syntax to use these commands are as follows :

unescape

   var foo = "Hello%20World"; // encoded string
   var bar = unescape("Hello%20World");
   console.log(bar);

decodeURI

   var foo = "Hello%20World"; // encoded string
   var bar = decodeURI("Hello%20World");
   console.log(bar);

decodeURIComponent

   var foo = "Hello%20World"; // encoded string
   var bar = decodeURIComponent("Hello%20World");
   console.log(bar);

The following charts are from w3schools.com

Windows-1252 and UTF-8 Encoding Reference

encoded

ASCII Control Characters Encoding Reference

enter image description here