admin管理员组

文章数量:1359416

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.

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.

Share Improve this question asked Aug 21, 2017 at 14:13 WaseemWaseem 5772 gold badges6 silver badges18 bronze badges 2
  • One way could be to store the cookie to a variable and then pass it through response object to the front end and then access it . – 0decimal0 Commented Aug 21, 2017 at 14:20
  • It is cumbersome to have to resend it on every request to the server, so saving it as a cookie would be much easier.. – Waseem Commented Aug 21, 2017 at 14:39
Add a ment  | 

2 Answers 2

Reset to default 3
       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.

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);
    }
  }
}

本文标签: javascriptHow to retreive cookies in front end code that is set by serversideStack Overflow