簡體   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