我在 Express 4 中使用 node.js 。我有 connect-flash 初始化的问题。我用不同的答案看了很多问题,但仍然无法解决我的问题。我尝试了许多 app.use()订单的组合,但仍然获得了TypeError req.flash is not a function
这是我当前的初始化顺序:
var app = express();
var index = require('./routes/index');
var users = require('./routes/users');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(sassMiddleware({
src: __dirname + '/public/sass',
dest: path.join(__dirname, 'public/css'),
debug: true,
outputStyle: 'compressed',
prefix: '/css'
}));
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
app.use(i18n({
translationsPath: path.join(__dirname, './locales'),
siteLangs: ["es","en"]
}));
app.use(function (res,req,next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
next();
});
app.use('/', index);
app.use('/users', users);
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
感谢您的帮助。
答案 0 :(得分:1)
app.use(function (res,req,next) {
//...
})
此函数中的req和res参数顺序错误。