簡體   English   中英

如何在 fetch api 中處理空響應

[英]How to handle null response in fetch api

我構建了一個 react-native 應用程序並使用fetch api來處理服務器請求,如果從服務器返回的 json 不為空,它工作正常,但如果來自服務器的響應為空,它會給我一個錯誤——“Json 解析錯誤:Unexpected 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.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);
}

如果 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);
            })

如果您想檢查空的響應請求

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.
  }
}

暫無
暫無

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

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