我尝试使用Cookie来强制使用ExpressJS 4.2和cookier-parser进行用户会话,但我找到的所有文档都是Expressjs 3.x或更早版本。
有人能指出我正确的方向吗?
文档或代码段将不胜感激。
提前致谢!
==
我想使用PassportJS使用MongoDB对本地用户进行身份验证,除了这条路线外,一切正常(ensureAuthenticatad总是重定向到/,即使在MongoDB中找到用户/通行证
// reusable middleware
function ensureAuthenticated(req,res,next) {
if(req.isAuthenticated()) {return next();}
res.redirect('/'); // if failed...
}
router.get('/panel', ensureAuthenticated,function(req, res){
res.render('panel', {obj: testArr});
});
那是因为ensureAuthenticated无法找到活动的cookie。
我的app.js配置如下:
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport')
var mongoose = require('mongoose');
var flash = require('connect-flash');
//Routes
//=====================================================================
var routes = require('./routes/index');
var admin = require('./routes/admin');
var panel = require('./routes/panel');
//Express configuration
//======================================================================
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
/*app.use(favicon());*/
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser('secret'));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/', admin);
答案 0 :(得分:1)
您需要使用https://www.npmjs.org/package/express-session初始化基于Cookie的会话
var session = require('express-session');
//code
app.use(session({secret: 'keyboard cat'}));