简体   繁体   中英

using express and sqlite3

so I have a database called user.db and the table are user_id, username, hashpassword.

when I call this function from the main thread it works find

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

but when im calling it from the express funcation

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"})
}
    });

it's printing undefined

can someone please tell me why when I call the function from another script or in the main thread it works fine but when it from the app.post() it doesn't work

SQLite3 functions are asynchronous, so your code can't assume it gets a return value. But more important than that, you forgot to work with Express's concept of middleware functions. Let's fix that. First, let's define our user check function as a middleware function, using normal JS conventions for naming things, not Python conventions.

First, checking for a cookie value:

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

Then, checking the user's login:

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`);
  });
}

And now we can use this in a proper express chain:

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
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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