简体   繁体   中英

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.

 httpOnly: true

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

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

Set the value to false instead.

Except set to httpOnly: false , which is required by access javascript access cookies, you have to using for-of instead of for-in

function getCookie(cname) {
  var arrayb = document.cookie.split(";");
  for (const item of arrayb) {
    if (item.startsWith("Token=")){
        return item.substr(6);
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM