简体   繁体   English

如何自定义快递中的cookie?

[英]how to customize cookie in express?

I am using express-session in my project: 我在项目中使用express-session

app.use(session({
  name: "server-session-cookie-id",
  secret: 'express secret',
  maxAge: 1000 * 3600 * 24,
  saveUninitialized: true,
  resave: true,
  store: new RedisStore({client: redisClient, ttl: 260, db: 2}),
}))

express-session will generate a cookie named server-session-cookie-id when I first visit my application. 当我第一次访问我的应用程序时, express-session将生成一个名为server-session-cookie-id

But, in my situation I want to append some information in cookie, something like this: 但是,在我的情况下,我想在Cookie中添加一些信息,如下所示:

cookie['server-session-cookie-id'] + uuid

how can I change the cookie when the cookie first time generate? 第一次生成Cookie时,如何更改Cookie?


EDIT 编辑

I think I ask the wrong question, what I want is when first visit my application(any page), I just create a cookie named uuid . 我想我问错了一个问题,我想要的是第一次访问我的应用程序(任何页面)时,我只是创建了一个名为uuid的cookie。

You can set a cookie using res.cookie and node-uuid . 您可以使用res.cookienode-uuid设置cookie。

npm install node-uuid --save

var uuid = require('uuid');

Then in your middleware of your main application just check for a user object: 然后在主要应用程序的中间件中检查user对象:

app.use(function(req, res, next) {
    if (!req.user) {
        res.cookie('uuid', uuid.v4());
    }
    next();
}

Assuming you have a user object on the req request object in the case of using express-session with passport . 假设在对passport使用express-session的情况下,您在req请求对象上有一个user对象。

如果您真的只是想在其上设置uuid(如您在评论中所述)的新cookie,则可以在Express中执行此操作以响应任何传入请求:

res.cookie('uuid', uuid);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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