sanjay gouri
sanjay gouri

Reputation: 21

TypeError: Cannot read property 'name' of undefined

When i type the username which is there in Table "fun" i am not facing any error but when i type wrong name that is the name which is not there in the table am facing error this is the error and code is attached below.

    app.post('/Fu',function(req,res,next){

        var username = req.body.uname;
        var password = req.body.pwd;


         con.query('SELECT name FROM fun WHERE name = "' + username +'" ',function(err, result,fields) {


            var w = result[0].name;  

            if( username == w ){
         console.log("login successful");

         }
         else{
              console.log("login not successful");       
                   }
     }

});

           res.send("success1");
           });

can someone please help with the error.

Upvotes: 0

Views: 1671

Answers (2)

Samuel
Samuel

Reputation: 1421

This error is probably related to the fact that, when username is not present in the table, result will be set to and empty array []. That means that it has no elements at all, so result[0] is undefined.

Make sure to check for that before trying to get result[0].name.

Also, I would suggest you a few things:

1) Add error checking before anything else;

2) You do not need to check if the name is equal to the result. The query you wrote will only return entries that already match that requirement;

3) Send the responses inside the callback function, otherwise, the user will get the "success1" answer before the query has even finished executing.

Here follows the resulting code:

app.post('/Fu',function(req, res, next){
    var username = req.body.uname;
    var password = req.body.pwd;

    con.query('SELECT name FROM fun WHERE name = "' + username +'"', function(err, result,fields) {
        if (err) {
            response.sendStatus(500);
            return;
        }

        if (result.lenght > 0) {
            res.send('Login was successful');
        } else {
            res.send('Login was not successful');
        }
     });
});

Upvotes: 1

bbuckley123
bbuckley123

Reputation: 1979

Your problem is here:

var w = result[0].name;

Because the result set at [0] doesn't exist (query came back with nothing). you are trying to get the name value from something that is undefined.

Do something like this:

var w
if (result[0]) {
    w = result[0].name
} else {
    //your logic to handle this scenario
}

That assumes that whatever db querying library you use will return an array, even if empty. If it returns undefined instead of an empty array, your if statement would need to look more like: if (result && result[0])

Upvotes: 0

Related Questions