无法使用nodejs在express + passport中设置cookie

时间:2014-05-22 16:32:16

标签: express passport-local

这里我试图在用户登录时选择记住复选框时设置cookie,但是甚至是console.log(“hello”);没有用。

// process the login form
        app.post('/login',passport.authenticate('local-login', {
            successRedirect : '/profile', // redirect to the secure profile section
            failureRedirect : '/login', // redirect back to the signup page if there is an error
            failureFlash : true // allow flash messages
            }), function(req, res) {
            console.log("hello");

            if (req.body.remember) {

              req.session.cookie.maxAge = 1000 * 60 * 3;
            } else {
              req.session.cookie.expires = false;
            }
          res.redirect('/');
    });

但我尝试使用express.session直接设置它可以正常工作如下

app.use(express.session(
    {   secret: 'sessionmaxageset',  
        cookie: { maxAge : 3600000 } 
    } 
)); // session secret

1 个答案:

答案 0 :(得分:1)

以下代码主要基于http://runnable.com/UTlPPF-f2W1TAAET/how-to-use-cookies-in-express-for-node-js。我正在使用Express 4.2.0,因此必须使用npm安装正文解析器和cookie解析器中间件。 New middleware现在正在取代名为cookies.js和keygrip.js的cookie解析器。

SERVER.JS

    var express = require('express');
    var app = module.exports = express();
    var bodyParser = require('body-parser');
    var cookieParser = require('cookie-parser');
    var http = require('http');
    var logger = require('morgan');
    var colours = require('colors');

    var port = process.env.PORT || 4000;        //set the port

    // parses request cookies, populating
    // req.cookies and req.signedCookies
    // when the secret is passed, used 
    // for signing the cookies.
    app.use(cookieParser('secret-string'));

    // parses json, x-www-form-urlencoded, and multipart/form-data
    app.use( bodyParser() );
    app.use( logger() );

    app.get('/', function(req, res) {

     if (req.cookies.remember) {
        res.send('Remembered :). Click to <a href="/forget">forget!.');
      } 
      else {
       res.send('<form method="post">

Check to <label>'+ '<input type="checkbox" name="remember"/> remember me </label> /' + '<input type="submit" value="Submit"/>.

'); } }); app.get('/forget', function(req, res) { res.clearCookie('remember'); res.redirect('back'); }); app.post('/', function(req, res) { var minute = 60 * 1000; if (req.body.remember) res.cookie('remember', 1, { maxAge: minute }); res.redirect('back'); }); var server = app.listen(port, function() { console.log('Listening on port %d' .green , server.address().port) });