繁体   English   中英

使用 express 和 sqlite3

[英]using express and sqlite3

所以我有一个名为 user.db 的数据库,表是 user_id、用户名、hashpassword。

当我从主线程调用这个函数时,它会找到

function check_login(username, hashpassword){
 user_db.all("SELECT * FROM users", [], (err, rows)=>{
     console.log(rows)
 });}

但是当我从 express 函数调用它时

app.post("/log_in/:cookie", (req, res) =>{
let cookie = req.params.cookie;
if (cookie != "")
{
    let user_id = check_login(req.body.username, req.body.hashpassword);
    console.log(user_id);
    if( user_id != ""){
        let code = create_code(get_info_by_cookie(cookie, user_id));
        res.json({"code":code})
    }
    else{
        res.json({"error":"username or password doesn't match"})
    }

}
else{
    res.json({"error":"no cookie was given"})
}
    });

它正在打印 undefined

有人可以告诉我为什么当我从另一个脚本或主线程调用函数时它工作正常但是当它从 app.post() 时它不起作用

SQLite3 函数是异步的,所以你的代码不能假设它得到一个返回值。 但更重要的是,您忘记使用 Express 的中间件功能概念。 让我们解决这个问题。 首先,让我们将我们的用户检查函数定义为一个中间件函数,使用正常的 JS 约定命名事物,而不是 Python 约定。

首先,检查 cookie 值:

function checkCookie(req, res, next) {
  let cookie = req.params.cookie;
  if (!cookie)  return next(new Error("no cookie found"));
  next();
}

然后,检查用户的登录:

function checkLogin(req, res, next) {
  let username = req.body.username,
      hashpassword = req.body.hashpassword;

  user_db.all("SELECT * FROM users", [], (err, rows) => {
    if (err) return next(err);
    // ...
    // You code goes here. You didn't show any, so I'm not inventing any either.
    // ...
    if (hasAccess) return next();
    return next(new Error(`user ${username} does not have access`);
  });
}

现在我们可以在适当的快递链中使用它:

app.post("/log_in/:cookie", checkCookie, checkLogin, (req, res) => {
    // We KNOW this user has a cookie set, and the their login is good.
    // So all this function has to do is form whatever response you need
    // given that those two things are true
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM