【问题标题】:Is express-session not working with express 4.13?express-session 不能与 express 4.13 一起使用吗?
【发布时间】:2015-11-22 17:38:49
【问题描述】:

据我所知,我已经根据documentation 为快速会话设置了会话。但是我的cookie没有被创建!根据文档,您所要做的就是设置 request.session 值,并且应该自动设置 cookie。我不确定是什么伏都教能做到这一点,但魔法似乎被打破了。只是为了确保我根据here 给出的示例进行了验证。我错了吗?这些是否缺少一些关键信息?

   //login route handler
   app.post('/users/login/', function (req, res) {

   //... get the row from DB, check the pass then set session

   this.bcrypt.compare(password, row.hashed, function(err, passwordsMatch) {
            if( passwordsMatch === true)
            {
                //set the session variable 'user'
                req.session.user = row;
                res.send(row);
            }
        });

所以我想知道我做错了什么,还是最新版本有错误?我可以检查我的数据库,并且确实在会话表的行上看到了正确的会话变量!

//Here's my "configuration" of express-session. 
app.use(function (req, res, next) {
    res.header('Access-Control-Allow-Credentials', 'true');
    next();
});

var storeOptions = {
  //my database options (this works, it makes rows in db table)
};

var sessionStore = new SessionStore( storeOptions );

app.use(session({
    name:'yay_session',
    secret: 'some secret this is now',
    resave: true,
    saveUninitialized: false,
    cookie: { maxAge: 600000,httpOnly: false, domain:'localhost' },
    store: sessionStore
}));

为什么我的客户端 cookie 没有设置?它不会显示在资源调试面板中。所以我想知道最新的 4.13.3 版本与 express-session 1.11.3 协同工作是否存在错误。这是截至 8 月 27 日的最新数据。

【问题讨论】:

    标签: javascript node.js express login express-session


    【解决方案1】:

    使用下面的代码让会话在 EXPRESS JS V 4 中正常工作:-

        var express = require('express');
        var session = require("express-session");
        var cookieParser = require('cookie-parser');
        var app = express();
        app.use(cookieParser());
        var MemoryStore =session.MemoryStore;
        app.use(session({
            name : 'app.sid',
            secret: "1234567890QWERTY",
            resave: true,
            store: new MemoryStore(),
            saveUninitialized: true
    }));
    

    【讨论】:

    • 这个问题浪费了我将近一天的时间。非常感谢。
    • 请说明您想做什么。在尝试了这个之后,什么都没有解决。
    【解决方案2】:

    必须保存会话。

    req.session.save(function(err) {
      // session saved
    })
    

    更多详情请关注express-session page。

    【讨论】:

    • 不真实,来自文档:This method is automatically called at the end of the HTTP response if the session data has been altered
    猜你喜欢
    • 2021-12-10
    • 2017-04-10
    • 2011-11-04
    • 2021-04-24
    • 2016-02-28
    • 2018-03-07
    • 1970-01-01
    • 2018-10-10
    • 2019-03-20
    相关资源
    最近更新 更多