繁体   English   中英

在Express.js中显示Flash消息的最佳方法是什么?

[英]What is the best way to display Flash messages in Express.js?

我在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}}

假设您发布的最后一部分代码是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 !!')
   });
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM