如果axios請求失敗,如何獲取后端接口返回的狀態碼及錯誤信息


這兩天在工作中遇到一個問題,一個請求返回400錯誤,我需要向用戶展示后端返回的錯誤信息,但是用普通的catch方法只能獲取到瀏覽器返回的400錯誤提示,不能獲取到后端返回的,后經查閱得出下面方法:
axios.get('/user/12345') .catch(function (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); } console.log(error.config); });
 

參考文檔: https://segmentfault.com/q/1010000011190809/a-1020000011210688


免責聲明!

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



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