2017-06-28 84 views
1

我有在我的反應應用Axios公司請求,爲此,我下面的axios npm docs.無法捕捉和記錄來自一個Axios公司請求

這是我的愛可信請求

axios.post(helper.getLoginApi(), data) 
     .then((response) => { 
      console.log(response); 

      this.props.history.push(from.pathname) 
     }) 
     .catch((error)=> { 
      console.log(error); 
     }) 
錯誤響應

我能夠成功地在成功的請求上記錄數據。然而,當我故意產生錯誤並嘗試CONSOLE.LOG它,我沒有得到的結果,而不是記錄,我只看到

POST http://localhost:3000/login 401 (Unauthorized) :3000/login:1
Error: Request failed with status code 401 login.js:66

at createError (createError.js:16)

at settle (settle.js:18)

at XMLHttpRequest.handleLoad (xhr.js:77)

但是當我去網絡選項卡在Chrome控制檯中,我可以看到低於響應返回。

enter image description here

感謝提前的幫助。

+0

您是否嘗試過包裝你的愛可信爲'嘗試{}趕上(E){ '聲明?你有沒有試過在'then'裏面檢查'response.status'?只是一些想法 - 我不知道爲什麼它不會工作 – lumio

+0

@lumio,正如我所說,然後,我能夠成功地記錄'response.data'而不是在'.catch'塊中 – Jagrati

+0

即使我自己使用axios我不確定當狀態不是'2xx'時axios總是失敗。當'response.status'不是200時,你有沒有嘗試在'then'內引發錯誤? – lumio

回答

5

Github Docs。愛可信的請求的響應看起來像

{ 
    // `data` is the response that was provided by the server 
    data: {}, 

    // `status` is the HTTP status code from the server response 
    status: 200, 

    // `statusText` is the HTTP status message from the server response 
    statusText: 'OK', 

    // `headers` the headers that the server responded with 
    // All header names are lower cased 
    headers: {}, 

    // `config` is the config that was provided to `axios` for the request 
    config: {}, 

    // `request` is the request that generated this response 
    // It is the last ClientRequest instance in node.js (in redirects) 
    // and an XMLHttpRequest instance the browser 
    request: {} 
} 

所以基本上catch(error =>)實際上只是catch(response =>)

,所以你可以登錄error.response.data,你應該能夠看到您的回覆消息。

When you log console.log(error) , what you see is the string returned by the toString method on the error object.

據對同一文檔的錯誤處理部分,您可以捕捉類似錯誤響應

axios.post(helper.getLoginApi(), data) 
     .then((response) => { 
      console.log(response); 

      this.props.history.push(from.pathname) 
     }) 
     .catch((error)=> { 
      if (error.response) { 
       // The request was made and the server responded with a status code 
       // that falls out of the range of 2xx 
       console.log(error.response.data); 
       console.log(error.response.status); 
       console.log(error.response.headers); 
      } else if (error.request) { 
       // The request was made but no response was received 
       // `error.request` is an instance of XMLHttpRequest in the browser and an instance of 
       // http.ClientRequest in node.js 
       console.log(error.request); 
      } else { 
       // Something happened in setting up the request that triggered an Error 
       console.log('Error', error.message); 
      } 
     }) 
+0

感謝您的快速響應,我會盡力讓你知道。 – Jagrati

+1

謝謝Shubham,我能夠得到錯誤的迴應。還要感謝提到爲什麼它不適用於我的情況 –