Reputation: 5
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!
Upvotes: 0
Views: 1273
Reputation: 4097
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;
}
});
Upvotes: 1