如何在html视图中为nodejs显示flash消息

时间:2016-08-25 18:56:20

标签: node.js

此功能用于登录身份验证。我希望在身份验证失败时在浏览器中显示警报消息。我无法使用警报,因为在节点警报中未定义所以我正在尝试使用闪存来显示警报消息。我可以使用它吗如果还有其他方法,请建议。

login : function(req, res) {
        var sess;
        sess = req.session;
        sess.user = req.body.username;
        if (sess.user) {

            /*
             * This line check Session existence. If it existed will do some
             * action.
             */
            var db = req.app.get('db')();
            // console.log(db);
            var Username = req.body.username;
            var Password = req.body.password;
            console.log('u r here');

            if (!Username.trim())
            {
                console.log('Incorrect username');
                // res.end('Incorrect username');
                res.redirect('/login');
            }
            else if (!Password.trim())
            {
                console.log('Incorrect Password');
                // res.end('Incorrect Password');
                res.redirect('/login');
            }
            else
            {
                var queryString = 'SELECT * from admin_info where user_name= ? And password=?';
                console.log(queryString);
                db.query(queryString, [ Username, Password ], function(error, rows, fields) 
                {
                    if (error) 
                    {
                        console.log(error);
                        res.end(error);
                    } 
                    else 
                    {
                        console.log('u r in function');
//                      console.log(Username + " " + Password);
        //              console.log(rows[0].id);
                        if(rows.length>0)
                        req.session.user_type_id=rows[0].user_type_id;
//                      req.session.userName =rows[0].username;
                        if (rows.length > 0) {
                            var str = '';

                            for (var i = 0; i < rows.length; i++) {
                                str = str + rows[i].Username + '\n';
                            }

                            module.exports.user(req,res);

                        } else {
                            // dialog.info('invalid username or password');
                            // res.end('Invalid username or password');
                            // res.redirect('/login');
                            res.render('login', { messages: req.flash('info','hello') });

                        }
                    }

                });

            }
        } else {
            res.redirect('/login');
        }

    },

1 个答案:

答案 0 :(得分:0)

您需要在Node应用中使用模板引擎,例如EJS,才能将Flash消息传递给HTML。 Scotch.io的这个tutorial详细介绍了如何在Express应用程序中设置视图引擎。

例如,在EJS中,要实现flash消息:

<div class="alert alert-danger"><%= info %></div>

这将在该div中输出'hello'。