首页 > 解决方案 > 我试图在 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。

标签: node.jspassport.jsconnect-flash

解决方案


Flash 中间件只有单次读取。当您在 console.log() 中阅读时,请在显示后快速删除所有消息。所以删除你的 console.log 并再次运行它


推荐阅读