未定义的消息variablesNodeJS
我一直在遵循本教程为我的节点应用程序来实现身份validation: https : //scotch.io/tutorials/easy-node-authentication-setup-and-local
我遇到的问题是我运行应用程序时出现此错误:(我的代码是exacltly应该如何根据上述网站)。
我试图寻找一个答案,但我可以得到的最好的是添加这个函数到我的服务器代码:
app.use(function(req, res, next){ res.locals.message = req.flash(); next(); });
这加载应用程序没有任何错误,但是,消息似乎并没有显示在我的前端。 不完全确定为什么,但林只能得到这个问题,我可以实现消息没有任何问题在我的其他项目。
我已经在下面添加了我的github链接,但是我的代码里有一些我的代码:
routes.js
app.post('/signup', passport.authenticate('local-signup', { successRedirect : '/dashboard', failureRedirect : '/#contact', failureFlash : true }));
passport.js
if (user) { return done(null, false, req.flash('signupMessage', 'Email already in use!')); }
index.ejs
<% if (message.length > 0) { %> <div class="alert alert-danger"><%= message %></div> <% } %>
Github项目: https : //github.coventry.ac.uk/salmanfazal01/304CEM-Back-End
从错误我想你没有正确地传递给ejs
视图的variablesmessage
。
所以你有两个解决scheme
1-在您的routes.js
文件中,您需要在呈现index
视图时传递消息,这就是您所遵循的示例的完成方式。
所以改变
//GET homepage app.get('/', function(req, res) { res.render('index'); });
至
//GET homepage app.get('/', function(req, res) { res.render('index' , {message: <your data> }); });
2 – 使用res.locals
和res.flash
这是你find的解决scheme,但你实际上并没有在req.flash()
传递任何值
所以replace这个代码
app.use(function(req, res, next){ res.locals.message = req.flash(); next(); });
同
app.use(function(req, res, next){ req.flash("info" , "first message"); //here you add message under type info req.flash("info" , "second message"); // here you add another message under type info next(); });
并在你的route.js
app.get('/', function(req, res) { res.render('index' , {message : req.flash("info")}); //set message from req.flash type info }); //or app.get('/', function(req, res) { res.locals.message = req.flash("info"); //set locals.message from req.flash type info res.render('index'); });