过去一小时我一直在盯着这段代码,我不知道如何解决这个问题,我得到了'TypeError: req.flash is not a function
。我试过移动app.use(flash)
,但我仍然收到错误。我该如何解决这个问题?
var flash = require('connect-flash');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var handlebars = require('express-handlebars').create({
layoutsDir: path.join(__dirname, "views/layouts"),
partialsDir: path.join(__dirname, "views/partials"),
defaultLayout: 'layout',
extname: 'handlebars'
});
var expressValidator = require('express-validator');
var session = require('express-session');
var passport = require('passport');
var localStrategy = require('passport-local').strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/login');
var db = mongoose.connection;
// init app
var app = express();
var routes = require('./routes/index');
var users = require('./routes/users');
// view engine
app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');
app.set('views', path.join(__dirname, "views"));
app.use(expressValidator());
// bodyParser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// set static folder
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use(flash);
// express session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
// passport init
app.use(passport.initialize());
app.use(passport.session());
// Global Vars
app.use(function (req, res, next) {
res.local.success_msg = req.flash('success_msg');
res.local.error_msg = req.flash('error_msg');
res.local.error = req.flash('error');
next();
});
// set Port
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function () {
console.log('Server started on port ' + app.get('port'));
});
答案 0 :(得分:4)
每the documentation,请更改:
app.use(flash);
到此:
app.use(flash());
并且,将您的app.use(flash())
移到您的其他路线定义之前,但是在您的会话定义之后。
答案 1 :(得分:3)
您使用<Expander Header="Handle"
FontSize="15"
BorderBrush="Black"
Margin="3,0,2,1">
<Menu Background="White">
<VirtualizingStackPanel Orientation="Vertical">
<MenuItem x:Name="MenuArticle"
Header="Article"
Height="25"
FontSize="13"
Width="177"
Click="MenuArticle_Click">
<MenuItem x:Name="menuNewArticle"
Header="New article"
Height="25"
FontSize="13"
Width="187"/>
<MenuItem x:Name="menuHandleArticle"
Header="Handle article"
Height="25"
FontSize="13"
Width="187"/>
</VirtualizingStackPanel>
</Menu>
</Expander>
设置的中间件按照其声明的顺序执行,因此在您的情况下,将在会话处理之前调用Flash模块。
快速浏览一下connect-flash-docs会发现在设置其他与会话相关的中间件后应该调用app.use()
,所以请尝试将其移到某些行,这样可以解决您的问题。
来自connect-flash-docs的引用:
Flash消息存储在会话中。首先,通过启用cookieParser和会话中间件来照常设置会话。然后,使用connect-flash提供的flash中间件。