Home > Enterprise >  Express js if logic dosn't work it always return the same message
Express js if logic dosn't work it always return the same message

Time:11-02

when I execute this code it always returns the same message even if i send different email

  let message = "";
  const findQuery = "select email from Users where email = ?";
  const queryResult = await db.query(findQuery, [req.body.email]);
  if(queryResult[0] === req.body.email){
    message = "Welcome Back"
  }else if (queryResult[0] != req.body.email) {
    message = "No Access"
  }
  res.send(message);

i expect deffrent message

CodePudding user response:

i fix it its about truthy or falsy in js i add [0] and its work beacuse if you think about if you enter non-existing email and logged in the console that's what you will get [{}] an empty object and that empty object is truthy and thats the reason why it return the same answer notice the object destruction we make to take the specific row

const findQuery = "select email from Users where email = ?";
const [email] = await db.query(findQuery, [req.body.email]);
if(email[0]){
  res.send(email[0].email);
}else {
 res.send("Need To Register");
}

CodePudding user response:

You are doing the same lookup twice.

Here you are fetching all the emails that match req.body.email:

const findQuery = "select email from Users where email = ?";
const queryResult = await db.query(findQuery, [req.body.email]);

If queryResults isn't empty, it should always equal req.body.email. Therefore this if-selection is redundant.

if (queryResult[0] === req.body.email) {
  message = "Welcome Back";
} else if (queryResult[0] != req.body.email) {
  message = "No Access";
}

I think what you're trying to do is something like this:

const [email] = await db.query(findQuery, [req.body.email]).catch(err => {
  throw err;
});

if (email && email.length > 0) {
  message = "Welcome Back";
} else {
  message = "No Access";
}
  • Related