[英]How to add extra verification to map in Nodejs?
I have my code我有我的代码
// take data from and check email if it exists
const response = await client.getEntries({content_type:'user'});
let userData = response.items.map(i => i.fields).find(obj =>{
if(obj.email == user)
return true;
})
// return 401 status if the credential is not match.
if (user !== userData.email || pwd !== userData.password) {
return res.status(401).json({
error: true,
message: "Email or Password is Wrong."
});
}
It works very well until I fill in non-existent email ... then I get "UnhandledPromiseRejectionWarning -> Cannot read property 'email' of undefined" ... as far as I understand in this case "userData" is undefined as well as email.它工作得很好,直到我填写不存在的电子邮件......然后我得到“UnhandledPromiseRejectionWarning -> 无法读取未定义的属性'email'”......据我所知在这种情况下“userData”是未定义的电子邮件。
I tried to add else here我试图在这里添加其他
let userData = response.items.map(i => i.fields).find(obj =>{
if(obj.email == user)
return true;
else
return obj.email = "wrong";
})
But in this case IF checks only first element from map.但在这种情况下,IF 只检查地图中的第一个元素。 How to add extra verification?
如何添加额外验证? Or how to fix it?
或者怎么解决? Any idea
任何的想法
You have a lot of different approaches here.你在这里有很多不同的方法。 At the end of the day it is about making sure you don't read the property of the undefined variable.
在一天结束时,它是关于确保您没有读取未定义变量的属性。
response.items.map(i => i.fields).filter(i => !!i).find((obj = {}) =>{...}
let userData = response.items.map(i => i.fields).find((obj = {}) =>{...}
let userData = response.items.map(i => i.fields).find((obj = {}) =>{ if((obj || {}).email == user) return true; }
You're using the find()
method which can potentially returns undefined
.您正在使用
find()
方法,该方法可能会返回undefined
。 Therefore, you have to take into account that userData
can be undefined
, otherwise, as you've witnessed, the following if
condition will fail:因此,您必须考虑到
userData
可以是undefined
,否则,正如您所见,以下if
条件将失败:
if (user !== userData.email || pwd !== userData.password) {
}
You need to add an extra check at the beginning like this one:您需要在开头添加一个额外的检查,如下所示:
if (!userData || user !== userData.email || pwd !== userData.password) {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.