如何在 Express/NodeJS 中创建即显消息?

How to create flash messages in Express/NodeJS?

这个问题已经被问过一百万次了,但我从来没有真正理解答案,即使我理解了,它们也不适合我的特定需求。

我目前使用这个实现了 flash 消息:

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

您可以在此处查看代码:https://github.com/balderdashy/sails/blob/0506f0681590dc92986985bc39609c88b718a997/lib/router/res.js

你可以通过多种方式实现它,但这些是最简单的。

1:覆盖

您可以通过 "middlewares"

覆盖该功能
app.use( function( req, res, next ) {
    // grab reference of render
    var _render = res.render;
    // override logic
    res.render = function( view, options, fn ) {
        // do some custom logic
        _.extend( options, {session: true} );
        // continue with original render
        _render.call( this, view, options, fn );
    }
    next();
} );

我从以下摘录: 你可以在没有 lodash 等的情况下进行复制

2:在新函数中包装渲染

制作你自己的函数来包装会话 flashMessage,你可以使用 this 来发挥你的优势,我出于懒惰使用了一些 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.