Node.js 如何在Express/NodeJS中创建flash消息?
这个问题已经被问了一百万次了,但我从来没有真正理解过答案,当我理解的时候,它们并不适合我的具体需要 我目前使用以下方法实现了flash消息:Node.js 如何在Express/NodeJS中创建flash消息?,node.js,express,flash-message,Node.js,Express,Flash Message,这个问题已经被问了一百万次了,但我从来没有真正理解过答案,当我理解的时候,它们并不适合我的具体需要 我目前使用以下方法实现了flash消息: app.use(function(req, res, next){ res.locals.sessionFlash = req.session.sessionFlash; delete req.session.sessionFlash; next(); }); 当我想在路由中使用消息时,我必须像这样明确地回忆它: res.render
app.use(function(req, res, next){
res.locals.sessionFlash = req.session.sessionFlash;
delete req.session.sessionFlash;
next();
});
当我想在路由中使用消息时,我必须像这样明确地回忆它:
res.render('...', {
sessionFlash: res.locals.sessionFlash
});
有没有更简单的方法(最好是不需要手动从会话中提取消息的方法)?大型框架(如
sails.js
您可以在此处看到代码:
您可以通过各种方式实现它,但这些是最简单的
1:覆盖
您可以通过“中间件”
我从以下内容中提取了这段代码:
您可以不使用lodash等进行复制
2:在新函数中包装渲染
制作您自己的函数来包装会话flashMessage,您可以使用此
对您有利,出于惰性,我使用了一些es6语法,但可以很容易地用es5代码替换
res.sendView = function(path, options) {
this.render(path, {
sessionFlash: res.locals.sessionFlash,
...options
});
}
// now you can use res.sendView instead of res.render.
“压倒一切”的方法对我来说很有魅力,谢谢。
res.sendView = function(path, options) {
this.render(path, {
sessionFlash: res.locals.sessionFlash,
...options
});
}
// now you can use res.sendView instead of res.render.