Arjun Hegde Arjun Hegde - 5 months ago 41
Node.js Question

TypeError: Cannot read property 'username' of undefined in passportjs

app.get('/getUser', function(req, res) {

console.log(req.user.username);

res.json({'user':req.user.username});
});


When I login to passportjs, this does not return any error, but when I am not logged in, it shows
TypeError: Cannot read property 'username' of undefined
error, I need to send res.json only if it is defined,

app.get('/getUser', function(req, res) {

console.log(req.user.username);
if(typeof req.user.username!="undefined")
res.json({'user':req.user.username});
else
res.json({'user':"Anonymous"});
});


but it gives error for conditional statement, How do I error handle it?

Answer

Passport places user on the req object. If you have not performed authentication with Passport, there will be no user object on the request object. Therefore, req.user will be undefined. As you can probably imagine, undefined does not have a property named username, causing your error.

You probably want something like:

username = req.user ? req.user.username : "Anonymous"
res.json({'user':username}); 
Comments