簡體   English   中英

如何使用 fetch 處理響應 .json 和 .text?

[英]How to handle response .json and .text using fetch?

我正在獲取一個返回 json 的 API,但是當它出現錯誤時,它只返回一個文本(在帶有 express 的節點中,結果以.send('string') .json({})返回,錯誤以.send('string') ),但我無法修改 API

所以我試圖做一些讀取 json 的東西,但如果它是一個文本,它會進入.catch ,其中錯誤是文本。

這是我嘗試過但沒有成功的方法。

fetch(apiUrl)
    .then(res => {
        try {
            let json = res.json()
            return json
        } catch (error) {
            return new Promise((resolve, reject) => reject(res.text()))
        }
    })
    .then(res => {
        // get result from res.json() **res == res.json**
    })
    .catch(error => {
        // get result from res.text() **res == res.text**
    })

我怎樣才能做到這一點? 如何獲得res.json()在未來.then()但如果失敗,得到res.text().catch

編輯:

我想在.catch獲取.text 我不知道為什么,但是拋出res.text()不起作用。

理想情況下,您的客戶端應用程序應該知道預期的響應類型並具有調用適當方法的靜態代碼。


處理您的情況的另一種方法是檢查響應contentType並根據特定的響應標頭值調用.json().text()

handleResponseStatusAndContentType(response) {
  const contentType = response.headers.get('content-type')!;

  if (response.status === 401) throw new Error('Request was not authorized.');

  if (contentType === null) return Promise.resolve(null);
  else if (contentType.startsWith('application/json;')) return response.json();
  else if (contentType.startsWith('text/plain;')) return response.text();
  else throw new Error(`Unsupported response content-type: ${contentType}`);
}

用法:

return fetch(
  url,
  requestInit,
)
.then(response => handleResponseStatusAndContentType(response))
.catch(error => {
  console.error(error);
  return error;
});

另一種方法是最初將所有內容格式化為文本,然后才嘗試解析它,同時在解析問題的情況下拋出錯誤。

 fetch("http://maps.googleapis.com/maps/api/geocode/json?address=google") .then(res => res.text()) .then(body => { try { return JSON.parse(body); } catch { throw Error(body); } }) .then(console.log) .catch(console.error); fetch("http://maps.googleapis.com/maps/api/geocode/xml?address=google") .then(res => res.text()) .then(body => { try { return JSON.parse(body); } catch { throw Error(body); } }) .then(console.log) .catch(console.error);

暫無
暫無

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

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