問題:axios返回200狀態(tài)碼(即請求成功)卻走進了catch里面
原因:
1.當axios請求完成后走的時then的代碼塊,如果then代碼塊中存在錯誤代碼信息,這時就會進入catch中拋出異常(注意:此時控制臺并不會報錯,因為錯誤被catch捕獲了)
2.axios是異步發(fā)起,若發(fā)起后頁面刷新,那么就會丟失當前進程,導致接收不到。例如 form表單,點擊按鈕提交后,表單會刷新
補充知識:axios用catch的寫法與不使用catch有什么區(qū)別?
官網上的寫法:
1
2
3
4
5
6
7
|
axios.post(url, data) .then(response => { console.log(response); }) . catch (error => { console.log(error); }) |
公司項目的寫法:
1
2
3
4
5
6
|
axios.post(url, data) .then(response => { console.log(response); }, error => { console.log(error); }) |
之前一直沒有仔細研究過then和catch的寫法,事實上,這個不是 axios catch 的相關 而是關于 new Promise() 的then
阮一峰在 promise 文檔中有介紹。
一般來說,不要在then方法里面定義 Reject 狀態(tài)的回調函數(shù)(即then的第二個參數(shù)),總是使用catch方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
// bad promise .then( function (data) { // success }, function (err) { // error }); // good promise .then( function (data) { //cb // success }) . catch ( function (err) { // error }); |
上面代碼中,第二種寫法要好于第一種寫法,理由是第二種寫法可以捕獲前面then方法執(zhí)行中的錯誤,也更接近同步的寫法(try/catch)。因此,建議總是使用catch方法,而不使用then方法的第二個參數(shù)。
公司的寫法無法catch第一個參數(shù)的異常。
這樣寫可能容易看懂一些:
1
2
3
4
5
6
7
8
9
|
axios.post(url, data) .then(response => { //處理邏輯 }, error => { console.log( '接口報錯' ); }) . catch (error=>{ console.log( '處理邏輯出錯' ); }) |
1
2
3
4
5
6
7
|
axios.post(url, data) .then(response => { //處理邏輯 }) . catch (error=>{ console.log( '接口或處理邏輯出錯' ); }) |
以上這篇vue axios請求成功卻進入catch的原因分析就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://www.cnblogs.com/linjiangxian/p/13099078.html