How to get cookie value in expressjs

主宰稳场 提交于 2020-05-10 04:04:21

问题


I'm using cookie-parser, all the tutorial talk about how to set cookie and the time it expiries but no where teach us how to get the value of these cookie


回答1:


First note that Cookies are sent to client with a server request and STORED ON THE CLIENT SIDE. Every time the user loads the website back, this cookie is sent with the request.

So you can access the cookie in client side (Eg. in your client side Java script) by using

document.cookie

you can test this in the client side by opening the console of the browser (F12) and type

console.log(document.cookie);

you can access the cookie from the server (in your case, expressjs) side by using

req.cookies

Best practice is to check in the client side whether it stored correctly. Keep in mind that not all the browsers are allowing to store cookies without user permission.

As per your comment, your code should be something like

var express = require('express');
var app = express();

var username ='username';

app.get('/', function(req, res){
   res.cookie('user', username, {maxAge: 10800}).send('cookie set');
});

app.listen(3000);



回答2:


For people that stumble across this question, this is how I did it:

You need to install the express cookie-parser middleware as it's no longer packaged with express.

npm install --save cookie-parser

Then set it up as such:

const cookieParser = require("cookie-parser");

const app = express();
app.use(cookieParser());

Then you can access the cookies from

req.cookies

Hope that help.




回答3:


hope this will help you

var app=requir('express')();
app.use('/',(req,res) => {
  var cookie = getcookie(req);
  console.log(cookie);
});

function getcookie(req) {
  var cookie = req.headers.cookie;
  //user=someone; session=QyhYzXhkTZawIb5qSl3KKyPVN (this is my cookie i get)
  return cookie.split('; ');
}

output

[ 'user=someone',
'session=QyhYzXhkTZawIb5qSl3KKyPVN' ]


来源:https://stackoverflow.com/questions/44816519/how-to-get-cookie-value-in-expressjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!