[英]req.flash() not working when rest succeed
I had a problem flashing the req.flash('success','Page Edited!');
我在闪烁req.flash('success','Page Edited!');
遇到问题req.flash('success','Page Edited!');
on the admin/pages while I can easily flash req.flash('danger',"Page slug already exsists")
when rerendering the page with the correspoding error.在管理员/页面上,而我可以在req.flash('danger',"Page slug already exsists")
具有相应错误的页面时轻松闪烁req.flash('danger',"Page slug already exsists")
。 It only happens when I redirect and query to mongoDB.它仅在我重定向和查询到 mongoDB 时发生。
My code is我的代码是
router.post('/edit-page/:slug',function(req,res){
req.checkBody('title','title must have a value.').notEmpty();
req.checkBody('content','Content must have a value.').notEmpty();
var title = req.body.title;
var slug = req.body.slug.replace(/\s+/g,'-').toLowerCase();
if (slug=="")slug= title.replace(/\s+/g,'-').toLowerCase();
var content = req.body.content;
var id = req.body.id;
var errors = req.validationErrors();
if (errors){
res.render('admin/edit_page',{
errors:errors,
title:title,
slug:slug,
content:content,
id:id
});
console.log(errors)
}else{
Page.findOne({slug: slug,_id:{'$ne':id}}, (err,page)=>{
if (page){
req.flash('danger',"Page slug already exsists")
res.render('admin/edit_page',{
title:title,
slug:slug,
content:content,
id:id
});
console.log(errors)
}else{
Page.findById(id, function (err,page){
if(err){
console.log(err);
}else{
page.title=title;
page.slug=slug;
page.content=content;
page.save(function(err){
if(err) return console.log(err);
console.log('debug');
res.redirect('/admin/pages');
//this is the code that wont flash to another page
req.flash('success','Page Edited!');
});
}
});
}
});
}
});
The issue is that you redirect the user before setting the flash message in问题是您在设置 flash 消息之前重定向用户
res.redirect('/admin/pages');
//this is the code that wont flash to another page
req.flash('success','Page Edited!');
Reversing those lines should work.反转这些线应该有效。
It's not super clear from the docs, but res.redirect()
works just like res.send()
/ res.end()
(and is typically the last thing you do in a request handler).从文档中不是很清楚,但是res.redirect()
工作方式就像res.send()
/ res.end()
(并且通常是您在请求处理程序中做的最后一件事)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.