2017-07-18 109 views
0

我試圖處理HTTP ajax調用中的網絡相關問題。因此,我暫時停止了IIS中各自的API服務,並試圖調用關閉的API - http://localhost:1000/GetData

fetch("http://localhost:1000/GetData") 
    .then(handleErrors) 
    .then(function(response) { 
     return response.Json(); 
    }).catch(function(error) { 
     console.log(error); 
    }); 

我嘗試下面的代碼太

fetch("http://localhost:1000/GetData") 
.then(response => { 
     if(response) { 
      if (response.status === 200) { 
      alert('Super'); 
      return response.json(); 
      } else { 
      alert('Hai'); 
      return ''; 
      } 
     } else { 
      alert('Oooops'); 
      return ''; 
     } 
     }) 
.catch(function(error) { 
      console.log(error); 
     }); 

但它的失敗,直接擊中catch塊,而不會觸發任何alert及其引發錯誤。而且response.json();在成功塊,我不知道它是如何執行的。

TypeError: response.json is not a function 
Stack trace: 
onFetchError/<@http://192.168.4.159:3000/app.0df2d27323cbbeada2cd.js:9946:13 

請幫助我如何檢查狀態碼,以及如何處理網絡錯誤(即網絡不可用404,等)

簡稱網站:https://www.tjvantoll.com/2015/09/13/fetch-and-errors/

+1

您是否在所有這些if語句之前控制檯記錄了響應? –

+1

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch api不顯示'response.status',而是顯示'response.ok'。 .status似乎更像是一個XMLHttpRequest對象prop –

+1

呵呵,這根本不是jQuery相關的,fetch是一個原生的JS實驗性XHR函數 –

回答

0

基於this issue on Github,您可以嘗試識別catch塊中的錯誤類型。所以,類似這樣的東西可能適用於您的情況:

fetch("http://localhost:1000/GetData") 
    .then(response => { 
    alert("Super"); 
    return response.json(); 
    }) 
    .catch(err => { 
    const errStatus = err.response ? err.response.status : 500; 
    if (errStatus === 404){ 
     // do something 
    } else { 
     // do another thing 
    } 
    }); 
+1

它的失敗......目前它觸發'HTTP OPTIONS',它不返回任何響應如果請求服務器處於脫機狀態,則返回瀏覽器。我在我的問題中發佈了詳細信息https://stackoverflow.com/questions/45182002/handling-of-failure-status-in-http-options-ajax-call – 2017-07-19 05:57:36

相關問題