简体   繁体   English

无法获取要在Express 4中发送请求的Cookie

[英]Can't get cookies to send with request in Express 4

Here's my initial config: 这是我的初始配置:

var session         = require('express-session');
var cookieParser    = require('cookie-parser');
app.use(session({
  saveUninitialized: true,
  resave: false,
  genid: function(req) {
    return Services.misc.generateUUID()
  },
  secret: secret.toString()
}));
app.use(cookieParser(secret));

Then in my controller (it's routed through a dead simple router to a controller, which then renders appropriate actions based on a Rails-like naming convention) I'll do something like this: 然后在我的控制器中(它通过一个死掉的简单路由器路由到控制器,然后该控制器根据类似Rails的命名约定呈现适当的操作),我将执行以下操作:

var TestController = {
  noaction: function(req, res) {
    var locals = {
      billy: 'the goat'
    }

    console.log('req session'.red, req.session);
    res.cookie('test_cookie', 'Wu Tang Clan');

    this.services.render.view(req, res, this, 200, locals);
  }

module.exports = TestController;

Note that this.services.render.view is just a service so that I don't have to write res.render('./app/controllers' + controller + '/' + action) 请注意, this.services.render.view只是一项服务,因此我不必编写res.render('./app/controllers' + controller + '/' + action)

Note the res.cookie line in the controller ( docs on express.js ). 注意控制器中的res.cookie行( express.js上的文档 )。 That's what the official docs say to do and in fact, it's then set in the browser: 这就是官方文档所说的,实际上,它是在浏览器中设置的:

在此处输入图片说明

However, the line above res.cookie is a log and I would imagine we'd have test_cookie in it, but: 但是,在res.cookie上方的行是一个日志,我想我们会在其中添加test_cookie ,但是:

在此处输入图片说明

All I get is a standard blank cookie every time, even though it's set browser-side and supposedly sending. 每次,我得到的只是一个标准的空白cookie,即使它是在浏览器端设置的,也可以发送。

My question is: How do I properly set and receive cookies in Express 4? 我的问题是: 如何在Express 4中正确设置和接收Cookie?

答案是:每次nodemon每次重新启动服务器以传播代码更​​改时,都会清除会话。

Your code seems to be ok, as dsp_099 said, it is probably the nodemon. 正如dsp_099所说,您的代码似乎还可以,它可能是nodemon。 The express-session saves the data in-memory, so when you restart your server (with nodemon automatically) all the memory data is reseted. express会话将数据保存在内存中,因此,当您重新启动服务器(自动使用nodemon)时,所有内存数据都将被重置。

I you wanna persist the session data even if node is restarted, may i suggest you use redis-session (Redis Database) 我想即使重新启动节点也要保留会话数据,我是否建议您使用redis-session(Redis数据库)

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

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