[英]Axios 400 error request call then instead of catch
我有這個 function:
add(App, Params, Callback){
var self = this;
var Data = self.process_fields(Params)
self.$http.post(
paths.api + '/app/' + App.Permalink,
new URLSearchParams(Data)
).then(function (error, response) {
console.log("then");
if (typeof (Callback) == "function") {
Callback(true, response.data.data);
}
}).catch(function(error){
console.log("catch");
if(typeof error.response !== "undefined"){
errors.render(error.response.data.error)
}
if (typeof (Callback) == "function") {
Callback(false, null);
}
});
}
當我調用請求並收到 400 錯誤時,它調用 then 而不是 catch:
我找到了解決方案
在axios攔截器中不返回承諾引起的問題:
axios.interceptors.response.use((response) => {
return response;
}, (error) => {
if (!error.response) {
alert('NETWORK ERROR')
} else {
const code = error.response.status
const response = error.response.data
const originalRequest = error.config;
if (code === 401 && !originalRequest._retry) {
originalRequest._retry = true
auth.commit('logout');
window.location.href = "/login";
}
return Promise.reject(error)
}
});
添加return Promise.reject(error)
就像一個魅力
這是 Axios 的舊版本中的目的。
從 v0.11 開始, validateStatus
已添加到配置中。 我們可以使用此選項來指定有效的狀態代碼范圍。 默認情況下,有效代碼為 >= 200 且 < 300。
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
參考:https://github.com/axios/axios/issues/41#issuecomment-215100137
添加一個響應攔截器,如
axios.interceptors.response.use(function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response;
}, function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.