我在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)
&#13;
以下是我启动所有内容的代码:
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();
});
&#13;
这里是我的代码,我真正应用它:
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 !!')
}
});
}
&#13;
这类问题有一些相关的答案,但没有具体的flash消息。
这是我的html:{{#if error_msg}}
<div class="alert alert-danger">{{error_msg}}</div>
{{/if}}
答案 0 :(得分:0)
假设你发布的最后一段代码是一个快速端点的主体,我猜你在回调到select
时覆盖了你的快速回调变量req
和res
。此外,这不是request
库回调的当前函数签名,它应该是request
,而不是function (error, response, body)
。修复函数签名,使用唯一的变量名称,它应该工作:
function (req, res, err, body)