【问题标题】:Form input comparison to sqlite3 database in node.js表单输入与 node.js 中 sqlite3 数据库的比较
【发布时间】:2021-01-22 02:34:04
【问题描述】:

我对使用 node.js 和 sqlite3 比较陌生。我正在尝试检查通过表单输入的用户名和密码是否与保存在 sqlite3 db 中的用户名和密码匹配。如果输入的用户名/密码与数据库中的用户名/密码不匹配,我想引发错误,否则将用户发送到另一个页面。

相关表格:

<form action="/account" method="post">
            <div class="form-group">
                <label for="user">Name:</label>
                <input type="text" id="user" name="name">
            </div>
            <div class="form-group">
                <label  for="pass">Password:</label>
                <input type="password"  id="pass" name="password">
            </div>
           
            <button type="submit">Submit</button>

数据库创建和比较表格:

var db = new sqlite3.Database(':memory:');
db.serialize(function() {
        
    db.run("CREATE TABLE Accounts (id INTEGER, username TEXT, password TEXT, fullname TEXT");

    db.run(`INSERT INTO Accounts VALUES (1, "bob", "password", "Bob Bobson")`);       
    });
});
db.close();

app.get('/account', function (req, res) {
    db.all('SELECT * FROM Accounts', function(err, rows){
        rows.forEach(function (row){
           if (row.username == req.body.user)
           //go to success page

           if (row.username != req.body.usr)
         //list error
    
        });
       
        res.send();
    });
});

【问题讨论】:

    标签: javascript html node.js sqlite


    【解决方案1】:

    运行查询并从帐户表中检索所有行是不明智的。如果表太大,将花费大量时间。 最好使用参数进行“获取”查询并检索特定行(如果存在)。如果存在,则函数回调中的行参数将不会未定义。

    db.get("SELECT * from ACCOUNTS where username=? and password=?", 
     [req.body.user,req.body.password],function(err,row){
          if(typeof row!=='undefined' && row!=null){ console.log('user exists'); }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-18
      • 1970-01-01
      • 1970-01-01
      • 2020-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-24
      相关资源
      最近更新 更多