NodeJS和MySQL,处理行

时间:2017-01-12 12:47:33

标签: mysql node.js

我是NodeJS的初学者,我目前正在使用node,express和mysql包。我正试图检查这个人是否已经注册。

如果是,则应执行以下代码:

    req.session.user = user;
    req.flash('success_notification', 'You are logged in');
    console.log("creating session :" ,req.session.user);

但是,当我尝试检查它是否设置为true时,authenticated始终保持为“false”。

 if (authenticated === true)

有谁知道我做错了什么?

这是我处理登录尝试的代码:

router.post('/login', function (req, res) {
    var user = req.body.username;
    var password = req.body.password;
    var authenticated = false;

    var query = "Select * from  user where username = \'" + user + "\'" + " AND pw = \'" + password  + "\'";

    connection.query(query, function (err,rows,fields) {
        if (err) console.log(err);
        else if (rows.length) {
            authenticated = true;
            console.log(authenticated);
        }
        else {
            console.log('False Password or Username');
        }
    });

    console.log(authenticated);
    if (authenticated === true) {
        req.session.user = user;
        req.flash('success_notification', 'You are logged in');
        console.log("creating session :" ,req.session.user);
    }

    res.redirect('/');    
});

1 个答案:

答案 0 :(得分:0)

这是一个回调问题。

我遇到了同样的问题。

条件if (authenticated === true)在您的查询完成之前得到验证并且已经返回,因此只有在authenticated验证自身后true变为router.post('/login', function (req, res) { var user = req.body.username; var password = req.body.password; //var authenticated = false; var query = "Select * from user where username = \'" + user + "\'" + " AND pw = \'" + password + "\'"; connection.query(query, function (err,rows,fields) { var authenticated = false; //Encapsulate your authenticated variable since you won't need it outside this scope if (err) console.log(err); else if (rows.length) { authenticated = true; console.log(authenticated); } else { console.log('False Password or Username'); } /** Moved here */ console.log(authenticated); if (authenticated === true) { req.session.user = user; req.flash('success_notification', 'You are logged in'); console.log("creating session :" ,req.session.user); } res.redirect('/'); }); // Moved wihin the your query /* console.log(authenticated); if (authenticated === true) { req.session.user = user; req.flash('success_notification', 'You are logged in'); console.log("creating session :" ,req.session.user); } res.redirect('/'); */ });

您可以让它适用于任何类型的布尔查询返回的方法是将其包含在您的查询中以创建回调函数。

因此,如果您将条件封装在查询中,它应该可以正常工作。

{{1}}