0

所以我有一个名为 user.db 的数据库,该表是 user_id、username、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"})
}
    });

它正在打印未定义

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

4

1 回答 1

0

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
});
于 2020-02-10T01:01:57.227 回答