重定向后不会保存快速会话

时间:2014-07-27 12:56:17

标签: node.js session express

在我的制作应用中,将数据保存到会话然后重定向是完全不可靠的。保存会话后的console.log显示已附加数据。然后在重定向上,另一个console.log显示会话已重置。每3-5次尝试,会话将在重定向中持续存在,但它几乎不可靠。在我的开发应用程序中,这段代码完美无缺......

•我尝试更改快速会话的版本 •我尝试在server.js中移动会话中间件上方的静态文件夹 •我尝试过使用req.session.save()

UPDATE ****** 这是会话中间件的一个已知问题:https://github.com/expressjs/session/pull/69

这是我的server.js

// Module Dependencies
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var session = require('express-session');
var favicon = require('serve-favicon');
var methodOverride = require('method-override');

// Set Environment from ENV variable or default to development
var env = process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var config = require('./config/config');

// Set Port
var port = process.env.PORT || config.app.port;

// Connect to our MongoDB Database
// mongoose.connect(config.db);

// set the static files location /public/img will be /img for users
app.use(express.static(__dirname + '/public'));

// Express Session
app.use(session({
    secret: 'asfasfa3asfa',
    resave: true,
    saveUninitialized: true,
    cookie: {
        secure: false,
        maxAge: 2160000000
    }
}));

// Favicon
app.use(favicon(__dirname + '/public/img/favicon.ico'));

// Set Jade as the template engine
app.set('views', './app/views');
app.set('view engine', 'jade');

// Get req.body as JSON when receiving POST requests
app.use(bodyParser.json()); // parse application/json 
app.use(bodyParser.json({
    type: 'application/vnd.api+json'
})); // parse application/vnd.api+json as json
app.use(bodyParser.urlencoded({
    extended: true
})); // parse application/x-www-form-urlencoded

// override with the X-HTTP-Method-Override header in the request. simulate DELETE/PUT
app.use(methodOverride('X-HTTP-Method-Override'));

// routes ==================================================
require('./app/routes')(app); // pass our application into our routes

// start app ===============================================
app.listen(port);
console.log('****** App is now running on port ' + port + ' ******'); // shoutout to the user
exports = module.exports = app; // expose app

以下是保存会话的控制器:

// Module dependencies.
var config = require('../../config/config');

// Render Either Home Page or Dashboard Page If User is Logged In
var index = function(req, res) {

    console.log("Session At Home Page: ", req.session)

    if (req.session.user) {
        res.render('dashboard');
    } else {
        res.render('home');
    }
};


// Handle Authentication Callback
var callback = function(req, res) {
    // Get Access Token via Service-SDK
    Service.getAccessToken(req, function(error, tokens) {

        if (error) {
            console.log(error);
            return res.redirect('/');
        }

        // Otherwise, Save User Data & API Tokens To Session
        req.session.regenerate(function(err) {
            req.session.user = tokens.user_id;
            req.session.access_token = tokens.access_token;
            req.session.client_token = tokens.client_token;
            req.session.save(function(err) {
                console.log("Session Before Redirect: ", req.session);
                res.redirect('/');
            })
        });
    });
};

module.exports = {
    index: index,
    callback: callback
};

我的路线

app.get('/auth/service/callback', application.callback)
    app.get('/logout', application.logout);
    app.get('/', application.index);

1 个答案:

答案 0 :(得分:3)

Express 4中的livereload和express-session之间存在冲突。您可以在此处阅读更多相关信息https://github.com/expressjs/cookie-session/issues/14

但简而言之,必须在会话后调用livereload。就这样:

var express     = require("express");
var http        = require("http");
var session     = require("express-session");
var livereload  = require("connect-livereload");

var app = express();
app.set("port", 9090);

/**
 * First you must config the session
 */
app.use(session({
    secret: "keyboardcat",
    name: "mycookie",
    resave: true,
    saveUninitialized: true,
    cookie: { 
        secure: false,
        maxAge: 6000000
    }
}));
/**
 * Then you can config the livereload
 */
app.use(livereload())

/**
 * This simple url should create the cookie. 
 * If you call the livereload first, the cookie is not created.
 */
app.get("/",function(req,res){
    req.session.name = "blaine";
    res.end("ok");
});

/**
 * If you call the livereload first, the session will always return nothing
 * because there is no cookie in the client
 */
app.get("/me",function(req,res){
    var name = req.session.name;
    var message = "Hello [" + name + "]!";
    res.end(message);
});
http.createServer( app ).listen(
    app.get("port"),
    function(){
        console.log("server is running in port ", app.get("port"));
    }
)

如果您在会话配置之前调用livereload,则所有内容似乎都可以正常工作,但cookie不会持续存在。这是一个棘手的错误,我失去了整整一天。我希望这有助于某人。