Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retreive cookies in front end code that is set by server-side?

Here's the code at the nodejs server: (after npm install express and npm install cookie-parser)

const express = require('express');
var cookieParser = require('cookie-parser');
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

app.get('/setcookie', function (req, res) {
        res.cookie('Token', "exampletoken", {
            maxAge: 1000 * 60 * 60 * 24 * 30 * 12 * 3000,
            httpOnly: true
        }).send('Success!');
})

app.listen(80, function () {
  //console.log("listening on 80")
});

And the code on the website:

<html>
<head>
<script>
function onload(){
   alert(getCookie("Token"));
}

function getCookie(cname) {
    var allcookies = document.cookie;
    var arrayb = allcookies.split(";");
    for (item in arrayb) {
        if (item.startsWith("Token=")){
            var c=item.substr(5);
            return c;
        }
    }
}
</script>
</head>
<body onload="onload()>
</body>
</html>

It always shows an alert saying "undefined" no matter what I do. I can read the token from the server but I'm unable to read it in the front end. Also, if you host that on the localserver and try using it on chrome it won't work because of some web security issue, I used it on a custom webview (the one cordova sets inside the app). The reason behind this is that cordova automatically deletes the cookies after the end of every session and so I want to save them on the localstorage.

TL;DR: It shows "undefined" instead of reading the cookie on the front end (onload code) but I can still read it on the back end.

like image 412
Waseem Avatar asked Nov 22 '25 22:11

Waseem


1 Answers

       httpOnly: true

This tells the browser that it should make the cookie available only to HTTP (i.e. not to client side JavaScript).

To read it with client side JS, simply don't do that.

Set the value to false instead.

like image 51
Quentin Avatar answered Nov 25 '25 12:11

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!