簡體   English   中英

如何在React Native上使用訪存功能登錄API並捕獲登錄錯誤?

[英]How can I log in to an API and catch login errors using fetch on React Native?

我正在制作一個需要登錄API的應用程序。 我有一個登錄表單,該表單將ID號和密碼發送給API,並且API應該這樣響應:

[  
   {  
      "user_id":"032984",
      "user_number":"140521351",
      "token":"990nZtMtEUUMY"
   }
]

如果出現登錄錯誤,API將響應:

[
  {
    "ERROR": "INVALID PASSWORD | NOT FOUND 1SELECT user_id, lastname, password, user_number FROM user where user_number = 'INVALIDVALUE'",
  },
]

我希望能夠使用if語句捕獲登錄錯誤,例如在此JSON中是否存在ERROR對象,顯示警報,否則登錄並將user_id和token保存到可以在應用程序的不同屏幕中使用的變量中向API發送更多請求,以JSON獲取這些響應,並顯示我需要的數據。

我怎樣才能做到這一點?

到目前為止,這是我的登錄功能的代碼:

// login function
  _userLogin = () => {
    this.setState({ isLoggingIn: true, message: '' });

    // send request to API properly
    fetch("https://api.company.com/v4/users/json.php", {
      method: "POST",
      // our headers
      headers: {
          'Content-Type': 'application/json',
          'Connection': 'close',
          'Accept': '*/*',
          'User-Agent': 'InternalApp/0.1 (InternalApp; ReactNative) Expo/33',
          'Accept-Language': 'en-US;q=1.0',
          'Accept-Encoding': 'gzip, deflate'
      },
      // body of the request with number/password
      body: JSON.stringify({
        user_number: this.state.number,
        password: this.state.password,
      }),
    })
    .then(response => {
      return response.json(); // make it json?!
    }).then(responseData => {
      // debug messages
      console.log(responseData);
      console.log("Moving on to parsing JSON"); // CODE WORKS TO HERE

      // parse json
      var jsonObj = JSON.parse(responseData); // CODE STUCK HERE
      // debug messages
      console.log("JSON parsed");
      if (jsonObj.ERROR)
        console.log("Error caught");
      else
        this.setState(prevState => ({
          credentialJson: prevState.credentialJson = responseData,
          isLoggingIn: false,
        }))

      this.props.onLoginPress();
    })
  };

我真的是React Native和StackOverflow的新手,請原諒任何格式問題。 我希望我提供了足夠的細節。

您的提取庫fetch返回一個Promise因此,如果API實際上引發錯誤,則可以添加catch語句。

fetch(url).then().catch((error) => {
   console.log("Error", error);
});

另一件事是您的代碼停止在JSON.parse的原因是您已經在上一個.then子句( response.json() )中解析了json,因此您嘗試解析的對象不是字符串,而JSON.parse期望。

根據您對此答案的評論以及console.log(responseData)的輸出,您的responseData是一個數組,而您的數據是第一個數組元素內的Object。 通過responseData[0]訪問您的數據。 例如:

responseData[0].token
//Should return "990nZtMtEUUMY"

這是檢查錯誤集的方法:

if(responseData[0].ERROR){}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM