【问题标题】:What is the best way to display Flash messages in Express.js?在 Express.js 中显示 Flash 消息的最佳方式是什么?
【发布时间】:2025-12-04 06:55:02
【问题描述】:

我在 Ejs 框架中有 nodejs 应用程序,我是 java 脚本的新手, 我需要知道在 Node.js 中设置 flash 消息的正确方法是什么

下面给出的我的代码给我一个错误,像这样:

C:\Users\sad\Desktop\Node Application\routes\users.js:57
      req.flash('error_mesg', 'A User with this name already exisit !!')
         ^

TypeError: Cannot read property 'flash' of null
    at Request._callback (C:\Users\as\Desktop\Node Application\routes\users.js:57:10)
    at Request.self.callback (C:\Users\sa\Desktop\Node Application\node_modules\request\request.js:188:22)
    at emitTwo (events.js:106:13)
    at Request.emit (events.js:191:7)
    at Request.<anonymous> (C:\Users\sd\Desktop\Node Application\node_modules\request\request.js:1171:10)
    at emitOne (events.js:96:13)
    at Request.emit (events.js:188:7)
    at IncomingMessage.<anonymous> (C:\Users\sd\Desktop\Node Application\node_modules\request\request.js:1091:12)
    at IncomingMessage.g (events.js:291:16)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:74:11)
    at process._tickCallback (internal/process/next_tick.js:98:9)

这是我启动一切的代码:

var flash = require('connect-flash');

// Global VArs
app.use(function (req, res, next) {
  res.locals.success_msg = req.flash('success_msg');
  res.locals.error_msg = req.flash('error_msg');
  res.locals.error = req.flash('error');
  next();
});

下面是我真正应用它的代码:

var errors = req.validationErrors();

if(errors){
  res.render('register' ,{
    errors:errors
  })
}else{

   var newUser = {first_name,last_name, role,email,password,company,role}
   request({
       url: "http://127.0.0.1:8000/v1/dashboard/register/",
       method: "POST",
       json: true,   // <--Very important!!!
       body: newUser
   }, function (req, res, err, body){
      var status = res['statusCode']
       console.log(typeof(status));
       if (status = '400'){
       req.flash('error_mesg', 'A User with this name already exisit !!')


}

   });
 }

这类问题有一些相关的答案,但不是专门的闪现消息。

这是我的 html :{{#if error_msg}} <div class="alert alert-danger">{{error_msg}}</div> {{/if}}

【问题讨论】:

    标签: javascript node.js express npm


    【解决方案1】:

    假设您发布的最后一段代码是 express 端点的主体,我猜您在对 request 的回调中覆盖了您的 express 回调变量 reqres。此外,这不是request 库回调的当前函数签名,它应该是function (error, response, body),而不是function (req, res, err, body)。修复函数签名,使用唯一的变量名,它应该可以工作:

    var errors = req.validationErrors();
    
    if(errors){
      res.render('register' ,{
        errors:errors
      })
    }else{
       var newUser = {first_name,last_name, role,email,password,company,role}
       request({
           url: "http://127.0.0.1:8000/v1/dashboard/register/",
           method: "POST",
           json: true,   // <--Very important!!!
           body: newUser
       }, function (error, response, body){
           var status = response.statusCode;
           console.log(typeof(status));
           if (status = '400'){
           req.flash('error_mesg', 'A User with this name already exisit !!')
       });
     }
    

    【讨论】:

    • 嘿@Rob 它工作正常,但有时它会给我一个错误,例如 Error: Can't set headers after they are sent.
    • 如果代码比您发布的更多,可能会发生这种情况,当您多次调用res.send 的某个变体时会发生这种情况。确保您没有多次调用 res.send 的任何实例,并且该错误应该消失
    最近更新 更多