简体   繁体   English

TypeError:无法读取password.js中未定义的属性“用户名”

[英]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.

相关问题 如何修复TypeError:无法读取未定义的passportjs的属性“authenticate” - how to fix TypeError: Cannot read property 'authenticate' of undefined passportjs “ typeError:无法读取未定义的属性“用户名”。” - “typeError: Cannot read property 'username' of undefined.” 类型错误:无法读取未定义的属性“用户名”-- - TypeError: Cannot read property 'username' of undefined-- TypeError:无法读取未定义的属性“用户名”? - TypeError: Cannot read property 'username' of undefined? 未捕获的类型错误:无法读取未定义的属性“用户名” - Uncaught TypeError: Cannot read property 'username' of undefined 类型错误:无法从表单提交中读取未定义的属性“用户名” - TypeError: Cannot read property 'username' of undefined from Form Submit 为什么会这样? : TypeError: 无法读取 REACT 中未定义的属性“用户名” - why is this happening? : TypeError: Cannot read property 'username' of undefined in REACT TypeError:无法读取Node JS中未定义的属性“用户名” - TypeError: Cannot read property 'username' of undefined in Node JS (Nodejs, expressjs, mongodb) UnhandledPromiseRejectionWarning: TypeError: 无法读取未定义的属性“用户名” - (Nodejs, expressjs, mongodb) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'username' of undefined 未处理的承诺拒绝:TypeError:无法读取未定义的属性“用户名” - Unhandled promise rejection: TypeError: Cannot read property 'username' of undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM