Sqlite3 NodeJs登录时重定向

时间:2018-09-28 01:51:15

标签: node.js sqlite

我有一个要求,如果登录成功,则应该将用户重定向到欢迎页面,而如果登录失败,则用户应该收到错误消息。

我能够在控制台中打印数据,但是我只需要一些帮助就成功和失败将用户重定向到网页。

下面是app.js函数,通过它我可以在控制台上打印

app.post('/loginform', function (req, res, next) {

    let sql = `SELECT * FROM Users WHERE Username  = ? and Password = ?`;
    let Username = `${req.body.name}`;
    let Password = `${req.body.password}`;
    let success;

    db.get(sql, [Username, Password], (err, row) => {
        if (err) {
          return console.error(err.message);
        }
        return row
        ? console.log(`Login Success `+ row.ID, row.Username,row.Password)
        : console.log(`Sorry, your username and password are incorrect. Try again!`);
      });
});

1 个答案:

答案 0 :(得分:0)

我尝试将返回的结果打印为行,并根据值进行打印,我了解到登录失败时它将返回undefined,登录成功时它将返回该用户行的json数据。

所以我想出了以下解决方案。

db.get(sql, [Username, Password], (err, row) => {
        if (err) {
          return console.error(err.message);
        }
        console.log(row);
        if(row != undefined){
            res.redirect('/welcome.html');
        }
        else{
            res.write('<html><body>');
            res.write('<h1>Sorry your username and password are incorrect. Try again!</h1>');
            res.write('</body></html>');
            res.send();
        }
    });