app.get('/page', (req, res) => { res.send( ` <button type='button' id='increment'>Test</button><br/><br/> <button type='button' id='gcv'>Get cookie's value</button> <script> function getCookie(cname) { const name = cname + "="; const decodedCookie = decodeURIComponent(document.cookie); const ca = decodedCookie.split(';'); for(let i = 0; i < ca.length; i++) { let c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } document.getElementById('increment').onclick = async e => { // same-origin is needed for the server be able to send back the cookie const fr = await fetch('/renew', {credentials: 'same-origin'}); const jr = await fr.json(); console.log(jr); // will output 'Yay!' }; document.getElementById('gcv').onclick = async e => { console.log('cookie: ' + document.cookie); // will not show anything due to httpOnly true console.log('quickBrownFox: ' + getCookie('quickBrownFox')); }; </script> `); } ); let n = 1; app.get('/renew', (req, res) => { // Setting httpOnly to true makes the cookie not readable from browser's javascript. // More secure, avoids XSS attack. // a non-expiring cookie. yet it gets deleted when the browser is closed though res.cookie('quickBrownFox', n++, {httpOnly: true}); // persistent cookie for 7 days, stays when the browser is closed. Hmm.. that's obvious :) res.cookie('makulit', 'hey', { maxAge: 1000 * 60 * 60 * 24 * 7, httpOnly: true }); res.status(200).json({message: 'Yay!'}); }); app.listen(3000);
ES6 is upon us, Chrome certainly makes javascript beautiful.
Happy Coding!
No comments:
Post a Comment