react-native fetch return status code + json

前端 未结 2 749
你的背包
你的背包 2021-02-14 21:32

I use fetch in react-native to make API calls.

I need to get status code (200 , 401, 404 ) and the response data.

This work to get the response data :



        
2条回答
  •  被撕碎了的回忆
    2021-02-14 22:02

    Because the response of the API in the first then is a string not an object, you can't use the response like response.status. You should first convert the response to a JSON object and then use the status as response.status like the first example. The code should work properly:

    return fetch(url)
    .then(response => {
      const statusCode = response.status;
      let data;
      response.json().then(obj=>{
        data= obj;
        return { statusCode, data };
      });
    
    })
    .then(res => {
      console.log("reponse :", res); // <-------- i get a "promise"
     }).catch(error => {
      console.error(error);
      return { name: "network error", description: "" };
    });
    

提交回复
热议问题