【问题标题】:react-native fetch return status code + jsonreact-native fetch 返回状态码 + json
【发布时间】:2018-03-01 04:21:13
【问题描述】:

我在 react-native 中使用 fetch 来进行 API 调用。

我需要获取状态码(200、401、404)和响应数据。

获取响应数据的工作:

return fetch(url)
.then(response => {
  return response.json();
})
.then(res => {
  console.log("reponse :", res); // <-------- res is ok with data
 })    .catch(error => {
  console.error(error);
  return { name: "network error", description: "" };
});

现在我调整第一个然后获取状态码,但数据不是我除了

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

控制台日志:

  {statusCode: 200, data: Promise}

【问题讨论】:

    标签: react-native promise fetch


    【解决方案1】:

    response.json() 返回一个承诺,你应该等到它实现。为此,您可以使用 Promise.all 和两个元素组成的数组:statusCoderesponse.json() 调用:

    return fetch(url)
      .then(response => {
        const statusCode = response.status;
        const data = response.json();
        return Promise.all([statusCode, data]);
      })
      .then([res, data] => {
        console.log(res, data);
      })
      .catch(error => {
        console.error(error);
        return { name: "network error", description: "" };
      });
    

    //编辑 您可以创建一个处理响应的函数

    function processResponse(response) {
      const statusCode = response.status;
      const data = response.json();
      return Promise.all([statusCode, data]).then(res => ({
        statusCode: res[0],
        data: res[1]
      }));
    }
    

    然后使用 then()

     return fetch(url)
        .then(processResponse)
        .then(res => {
            const { statusCode, data } = res;
            console.log("statusCode",statusCode);
            console.log("data",data);
        }) .catch(error => {
        console.error(error);
        return { name: "network error", description: "" };
      });
    

    【讨论】:

    • 感谢您的帮助。我收到then([res, data] =&gt; { 的语法错误我将其更改为.then((res, data) =&gt; { console.log(res, data); }) 但此日志undefined undefined
    • 您遇到了什么错误?我使用 destructing 语法来获取变量的名称。如果您的 node.js 版本不支持,请使用数组索引:.then(res =&gt; console.log(res[0], res[1])
    • 这是错误:error: bundling failed: ..services.js: Unexpected token, expected , (176:22) 174 | return Promise.all([statusCode, data]); 175 | }) &gt; 176 | .then([res, data] =&gt; { | ^ 177 | console.log(res, data); 178 | }) 179 | .then(json =&gt; {
    • 否则下面的代码对我有用,非常感谢:.then(response =&gt; { const statusCode = response.status; const data = response.json(); return Promise.all([statusCode, data]); }) .then(res =&gt; { return {statusCode:res[0], data:res[1]} }) .then(json =&gt; { console.log("reponse :", json); ...
    • 类似的东西:function processResponse(response) { const statusCode = response.status; const data = response.json(); return Promise .all([statusCode, data]); .then(res =&gt; ({ response: res[0], data: res[1] })); }
    【解决方案2】:

    因为第一个then中API的响应是字符串而不是对象,所以不能像response.status那样使用响应。您应该首先将响应转换为 JSON 对象,然后像第一个示例一样使用response.status 的状态。代码应该可以正常工作:

    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: "" };
    });
    

    【讨论】:

    • 感谢您的帮助。我同意它是一个字符串而不是一个对象,应该是 jsonified。但是当我将它 jsonify 时,它的状态就被删除了
    • 不行,thenres 会在 then 之前在 response.json() 中被调用。
    • 我修复了这个错误。
    • 仍然不正确。还使用了一些反模式(嵌套承诺、闭包)。
    猜你喜欢
    • 2021-11-04
    • 1970-01-01
    • 2018-03-14
    • 2017-12-14
    • 1970-01-01
    • 1970-01-01
    • 2019-07-03
    • 2018-11-12
    • 2018-02-25
    相关资源
    最近更新 更多