简体   繁体   English

如何在Nodejs中添加额外的验证来映射?

[英]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.在一天结束时,它是关于确保您没有读取未定义变量的属性。

  1. You can filter undefined variables out of the dataset.您可以从数据集中过滤未定义的变量。

response.items.map(i => i.fields).filter(i => !!i).find((obj = {}) =>{...}

  1. You can place a default value您可以放置​​一个默认值

let userData = response.items.map(i => i.fields).find((obj = {}) =>{...}

  1. You can also place the default check at the if statement level您还可以将默认检查放在 if 语句级别

let userData = response.items.map(i => i.fields).find((obj = {}) =>{ if((obj || {}).email == user) return true; }

  1. You can also filter out the "non-existent email" from the API or however, you are getting the data.您还可以从 API 中过滤掉“不存在的电子邮件”,或者您正在获取数据。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM