【问题标题】:How to handle null response in fetch api如何在 fetch api 中处理空响应
【发布时间】:2017-01-16 20:46:08
【问题描述】:

我构建了一个 react-native 应用程序并使用 fetch api 处理服务器请求,如果从服务器返回的 json 不为空,它工作正常,但如果来自服务器的响应为空,它会给我一个错误- “Json Parse 错误:意外的 EOF”,下面是我用于获取的代码,我尝试在调试时设置断点,以查看从服务器返回 null 时响应的内容,我无法找到关于我可以在解析它之前进行一些检查,看看响应是否为空,所以需要帮助

return fetch(url, //service url{
 method: type,     // get or post
  headers: {
   'Accept': 'application/json',
   'Content-Type': contentType,
  },
  body: data    //some input parameters
}).then((response) => {
        return  response.json();
    })
    .then((responseJson) => {
      request.onSuccess(responseJson);   // success callback
    })
    .catch((error) => {
     request.onError(error);     // error callback
      console.error(error);
    });

【问题讨论】:

  • 试试/抓住response.json()。如果它失败了,你知道你有一个正确的响应,但不是有效的 JSON,并且可以相应地重新路由。 (fetch API 的.catch 部分不是用于捕获抛出,而仅用于捕获真正的网络/请求错误)

标签: javascript json react-native fetch


【解决方案1】:

如果您想检查响应请求是否为空

const response = await fetch(url, options); // your url and options

if (response.ok) {
  const contentType = response.headers.get('content-type');

  if (contentType && contentType.indexOf('application/json') !== -1) {
    const json = await response.json();
    successCb(json); // Write your script.
  } else {
    successCb(); // if the request is successful but the response is empty. Write your script.
  }
}

【讨论】:

    【解决方案2】:

    如果json响应null而不是使用response.json()使用response.text()

                fetch(path)
                .then(function (response) {
                    return response.text()
                }).then(function (data) {
                    resolve(data.length == 0 ? null : JSON.parse(data))
                }).catch(err => {
                    reject(err);
                })
    

    【讨论】:

      【解决方案3】:

      有一个很好的答案here,但在我的情况下,我需要在 response.text() 返回后访问响应对象:

      function buildResult(response) {
        // response.json() crashes on null response bodies
        // return {
        //   data: response.json(),
        //   identityToken: response.identityToken // sliding expiration...
        // };
      
        return new Promise((resolve, reject) => {
          response.text().then(body => {
            resolve({
              data: body.length ? JSON.parse(body) : null,
              identityToken: response.identityToken // sliding expiration...
            });
          }).catch(err => {
            reject(err);
          });
        });
      }
      
      //
      // the api fetch function
      //
      
      function apiFetch(url) {
        return fetch(url)
          .then(checkStatus)
          .then(parseIdentityToken)
          .then(buildResult);
      }
      

      【讨论】:

        猜你喜欢
        • 2017-02-09
        • 2017-03-07
        • 1970-01-01
        • 2016-07-13
        • 2017-08-23
        • 1970-01-01
        • 2023-02-02
        • 2017-02-21
        • 2016-09-01
        相关资源
        最近更新 更多