[英]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, 当我登录passport.js时,这不会返回任何错误,但是当我未登录时,它会显示
TypeError: Cannot read property 'username' of undefined
错误的TypeError: Cannot read property 'username' of undefined
仅在定义了内容时,才需要发送res.json,
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? 但是它为条件语句提供了错误,如何处理错误?
Passport places user on the req object. Passport将用户放置在req对象上。 If you have not performed authentication with Passport, there will be no user object on the request object.
如果尚未使用Passport执行身份验证,则请求对象上将没有用户对象。 Therefore, req.user will be undefined.
因此,req.user将是未定义的。 As you can probably imagine, undefined does not have a property named username, causing your error.
您可能会想到,undefined没有名为username的属性,从而导致您的错误。
You probably want something like: 您可能想要类似的东西:
username = req.user ? req.user.username : "Anonymous"
res.json({'user':username});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.