简体   繁体   中英

Cannot read property 'length' of undefined when trying to read the results of a MYSQL query

I've been stuck on this issue for a while and I could just be stupid, but I'm hoping it's not that bad. I've been tasked to create a simple system using NodeJS + Express + MYSQL. Where a user can login and out, while checking for already existing username/email

So the code that gives me the error I have currently (it has gone through many iterations and implementations)

var userExists;
var emailExists;

var userCheck = 'SELECT * FROM users WHERE uname =' + req.body.email;

connection.query(userCheck, function (error, results) {
    if (error) {
        userExists = true;
        res.json({
            status: false,
            message: 'there are some error with query'
        })}
        if (results.length > 0) {
            userExists = true;
            res.json({
                status: false,
                message: 'Username already exists'
            });
        } else {

            userExists = false;
        }
});

I get an issue of:

'TypeError: Cannot read property 'length' of undefined'

My head has been through a lot in the past 10 hours with this code but I'm hoping it's not too much of a rookie mistake! Any help will be appreciated!

Your current code will try to check the .length of results regardless of whether there's an error . If there's an error, results may be undefined , so proceeding to check results.length will throw. Consider return ing at the bottom of the if (error) block:

connection.query(userCheck, function (error, results) {
  if (error) {
    userExists = true;
    res.json({
      status: false,
      message: 'there are some error with query'
    });
    return;
  }
  if (results.length > 0) {
    userExists = true;
    res.json({
      status: false,
      message: 'Username already exists'
    });
  } else {
    userExists = false;
  }
});

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