fetch的使用--當無法判斷后台返回數據為什么類型時如何操作


需求:一個增刪改查頁面,當新增,刪除或者修改操作時不確定后台會返回的信息(會根據需求不同請求成功后可能返回message,可能什么都不返回)

問題:使用fetch進行請求時, Fetch API 的 Response 接口呈現了對一次請求的響應數據,response解析數據的方法我用到的為response.json()和response.text(),因為response可以獲取到狀態碼,請求狀態,但是在解析之前是不清楚返回到結果用哪種方式解析的,如果后台返回的為空還用json的方式就會報錯   "Unexpected end of JSON input"

解決:

在fetch請求后使用了三個then去處理各種狀態的返回值:

  1)第一個then判斷是否請求成功,失敗則直接返回錯誤信息

  2)成功則在第二個then中判斷mothed類型,若為增刪改狀態則返回response.text(),其他類型返回response.json()

  3)第三個then接收第二個then的返回值,若mothed類型為增刪改則判斷后台是否返回了message,返回則進行解析並渲染出返回值,若無返回值則不進行操作,其他類型則直接返回第二個then中的返回值


const checkStatus = response => {
 //當請求成功時直接返回response,失敗則進行json解析返回失敗信息
if (response.status == 200) { return response }else{ return response.json().then(json => { return Promise.reject(json) }) } };
export default function basicRequest(url, option) {
  const options = {
  expirys: isAntdPro(),
    ...option,
  };
  const fingerprint = url + (options.body ? JSON.stringify(options.body) : '');
  const hashcode = hash
    .sha256()
    .update(fingerprint)
    .digest('hex');

  const defaultOptions = {
    credentials: 'include',
  };
  const newOptions = { ...defaultOptions, ...options };

  if (
    newOptions.method === 'POST' ||
    newOptions.method === 'PUT' ||
    newOptions.method === 'DELETE' ||
    newOptions.method === 'PATCH'
  ) {
    if (!(newOptions.body instanceof FormData)) {
      newOptions.headers = {
        Accept: 'application/json',
        'Content-Type': 'application/json; charset=utf-8',
        ...newOptions.headers,
      };
      newOptions.body = JSON.stringify(newOptions.body);
    } else {
      newOptions.headers = {
        Accept: 'application/json',
        ...newOptions.headers,
      };
    }
  }

  const expirys = options.expirys && 60;
  if (options.expirys !== false) {
    const cached = sessionStorage.getItem(hashcode);
    const whenCached = sessionStorage.getItem(`${hashcode}:timestamp`);
    if (cached !== null && whenCached !== null) {
      const age = (Date.now() - whenCached) / 1000;
      if (age < expirys) {
        const response = new Response(new Blob([cached]));
        return response.json();
      }
      sessionStorage.removeItem(hashcode);
      sessionStorage.removeItem(`${hashcode}:timestamp`);
    }
  }
return fetch(url, newOptions)
    .then(checkStatus)
    .then(response => {
    //請求成功狀態下,method正常情況使用response.json()將結果返回,當進行增刪改時使用response.text(),在返回值為空或者有返回值是text()都不會報錯
if (newOptions.method === 'DELETE'|| newOptions.method === 'POST'|| newOptions.method === 'PATCH'|| newOptions.method === 'PUT') { return response.text(); } return response.json(); }).then(e=>{
    //獲取上一步返回的值,當method非增刪改狀態直接返回值,反之判斷返回值是否存在,若存在解析一下彈出信息,若不存在不做操作
if (newOptions.method === 'DELETE'|| newOptions.method === 'POST'|| newOptions.method === 'PATCH'|| newOptions.method === 'PUT') { if(e){ const msg = JSON.parse(e) if(msg.message){ notification.success({ message: msg.message }) } } } return e }) .catch(e => {//獲取錯誤信息並彈出 notification.error({ message: e.message }) })
}

首發於 博客園


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM