node.js - 我试图在 express.js 中显示 flash 错误消息,但 req.flash('error') 返回空数组
问题描述
在 authControllers.js 中,我重定向到 /signup 页面以及一条错误消息
const err = validationResult(req);
//find errors and convert to array
const reqErrors = err.array();
const errors = reqErrors.filter(e => e.msg !== 'Invalid value');
let messages = [];
//loops through erros and push them into messages array
errors.forEach((error) => {
messages.push(error.msg);
});
//check if we have error or not
** if (messages.length > 0) {
// Store error into flash , so we display it later
req.flash('error', messages);
res.redirect('/signup');
}else{**
//move further
return next();
}
}
在 userRoutes.js 中
userRouter.get('/',(req, res)=>{
console.log("hello from get route")
console.log(req.flash())
const errors = req.flash('error')
console.log(errors.length)
return res.render('signup',
{
title:"Chatting room Log in",
messages: errors,
// if error array > 0 then we have an error need to display
flag :errors.length > 0
}
);
});
当我运行程序时,这是以下 console.log(req.flash()) 输出:
{ error: [ '用户名是必需的,必须至少有 5 个字符。','电子邮件无效','密码是必需的,必须至少有 5 个字符。' ] }
但是,变量errors 是一个空数组,因此当我尝试输出errors.length 时。我得到了 0。它应该给我长度 3。
谢谢你帮助我!我正在使用 connect-flash、passport.js、express.js。
解决方案
Flash 中间件只有单次读取。当您在 console.log() 中阅读时,请在显示后快速删除所有消息。所以删除你的 console.log 并再次运行它
推荐阅读
- delphi - 我无法修复错误 SSL 例程:SSL23_GET_SERVER_HELLO:unknown protocol
- javascript - 当我单击 div 时如何隐藏/显示兄弟姐妹 div
- word - Word Mailing:如果合并字段段落编号,则交叉引用
- php - 递归函数返回问题
- javascript - mysql 表 AUTO 增量不断递增,而不是 1。像 41、51、61
- r - 修剪列中的空格
- laravel - Laravel - 如何在 chartjs 饼图中同时显示计数和百分比 (%)
- powershell - 将复制命令行从批处理转换为 powershell
- c# - C# 和 LINQ.XML 从 XML 中选择
- javascript - 键入自定义渲染器 [ Gatsby 和内容丰富的 Richtext ]