node.js 如何在expressjs中获取cookie值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44816519/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:19:43  来源:igfitidea点击:

How to get cookie value in expressjs

node.jsexpresscookies

提问by Keitaro Urashima

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

我正在使用 cookie-parser,所有教程都在讨论如何设置 cookie 以及它的到期时间,但没有教我们如何获取这些 cookie 的值

回答by Shanil Fernando

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.

首先请注意,Cookie 是通过服务器请求发送到客户端的,并存储在客户端。每次用户重新加载网站时,此 cookie 都会与请求一起发送。

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

因此您可以通过使用访问客户端(例如在您的客户端 Java 脚本中)的 cookie

document.cookie

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

您可以通过打开浏览器的控制台 (F12) 并键入在客户端进行测试

console.log(document.cookie);

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

您可以通过使用从服务器(在您的情况下,expressjs)端访问 cookie

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.

最佳做法是在客户端检查它是否存储正确。请记住,并非所有浏览器都允许在未经用户许可的情况下存储 cookie。

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

回答by Jishan mondal

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' ]

回答by M Mansour

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.

您需要安装 express cookie-parser 中间件,因为它不再与 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

然后你可以访问cookies

req.cookies

Hope that help.

希望有所帮助。