如何在ExpressJS中获得Cookie的价值 [英] How to get cookie value in expressjs

查看:76
本文介绍了如何在ExpressJS中获得Cookie的价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用cookie解析器,所有教程都讨论如何设置cookie及其过期时间,但是没有地方教我们如何获取这些cookie的值

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是随服务器请求发送给客户端的,并且存储在客户端

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(例如,在客户端Java脚本中) )

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

document.cookie

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

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

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

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

这篇关于如何在ExpressJS中获得Cookie的价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆