【问题标题】:How can I get the object items in Axios?如何在 Axios 中获取对象项?
【发布时间】:2021-11-19 11:39:50
【问题描述】:

这可能看起来很愚蠢,但我试图访问对象中的变量以登录,但我不能。

Array [
  Object {
    "Id": 1,
    "password": "1111111",
    "userName": "x@xx.xx",
    "userType": "Admin",
  },
  Object {
    "Id": 2,
    "password": "1234567",
    "userName": "deneme@xx.xx",
    "userType": null,
  },
]

如果我需要显示此示例,我需要到达 userNamepassword 字段以在登录端进行比较。

我试试这个;

axios.get('foo')
     .then(function (response) {   
       console.log(response.data.userName)
     });

我试试这个;

axios.post('foo', {
            userName: values.email,
            password: values.password
          }).then(user => {
            if(user.userName === values.email && user.password == values.password) {
              navigation.navigate("Home");
            } else {
              console.log(user.data.username)
              Alert.alert("Warning!",
                          "Please check your email or password", 
                          [{ text: 'Ok' }]);
            }
          }).catch(function (error){
            console.warn(error.message)
          });

我试试这个;

const userData = {
  email: values.email,
  password: values.password,
}

axios.get('foo', userData)
     .then(res => {
       responseData = res.data;
       if(responseData.status == 'success') {
         const user = responseData.user;
         navigation.navigate("Main");
       } else {
         alert('Something went wrong while login account');
       }
     });

我只需要访问对象上的用户名和密码字段。

【问题讨论】:

  • 您的回复是ArrayObjects。如果您想在Array 中访问Objects,请使用map()forEach 或简单的for 循环。
  • response.data.userName 不好。如果你想获取第一个用户名和密码,你应该response.data[0].userName; response.data[0].password
  • 我不想获得第一个用户。我想检查登录的用户是否在数据库中@GiovanniEsposito
  • 如何循环响应原生? @nithinpp
  • @developerysn response.data.forEach(user => { /*here you have the particular user*/ })

标签: javascript react-native axios


【解决方案1】:

基本上,在客户端验证用户凭据或在每个用户的 api 响应中进行比较是没有意义的。在服务器端执行此操作。

通过 api 发送用户凭据信息,如果凭据为真,则返回用户对象,如果凭据错误,则返回用户对象,然后只需检查 api 响应,如下所示

axios.post('foo', {
            userName: values.email,
            password: values.password
          }).then((response) => {
            if(response.user){
              //here user is either the user object or null
              //credentials are correct
            }else{
              //credentials are wrong
            }
          }).catch(err=> console.log(err))

在服务器端,你可能会做这样的事情

1. Get email and password from the api request
2. Verify something the credentials with the Database record 
3. Return the response with user object or null/false in case of incorrect credentials

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-17
    • 1970-01-01
    • 2021-09-22
    • 2018-07-07
    • 2021-04-24
    • 2022-12-05
    • 2021-08-09
    • 2014-07-18
    相关资源
    最近更新 更多