问题
Here i'm trying to set cookie when user select remember checkbox when user logins, but even the console.log("hello"); is not working.
// 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('/');
});
but i tried directly setting with express.session it works fine like below
app.use(express.session(
{ secret: 'sessionmaxageset',
cookie: { maxAge : 3600000 }
}
)); // session secret
回答1:
The following code is mainly based on http://runnable.com/UTlPPF-f2W1TAAET/how-to-use-cookies-in-express-for-node-js. I am using Express 4.2.0 so the body-parser and cookie-parser middleware has to be installed using npm. New middleware is now superseeding cookie-parser called cookies.js and keygrip.js.
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) });
来源:https://stackoverflow.com/questions/23812512/unable-to-set-cookie-in-express-passport-with-nodejs