當我嘗試執行此任務以更改密碼時,如果回應為 200 并且它還給我一個彈出視窗,則一切正常,但如果它沒有執行 else 陳述句,它就像沒有別的一樣。完全無視。
這是代碼
const submitForm = () => {
let form_data = new FormData();
form_data.append('old_password', formValues.oldpass);
form_data.append('new_password', formValues.newpass);
try {
axios.put(baseUrl '/change-password/', form_data,
{
headers: {
'Authorization': `Token ${token}`
}
}
).then((response) => {
const Swal = require('sweetalert2');
console.log(response.data);
if (response.status === 200) {
Swal.fire(
'Great!',
'Password updated successfully',
'success'
)
}
else {
alert('error ', 'password has not been changed !!');
}
});
} catch (error) {
console.log(error);
}
};
請幫助我是新來的反應,我已經有這個問題好幾天了。
uj5u.com熱心網友回復:
如果狀態碼不是 2xx,Axios 會拋出回應。這意味著如果您得到例如 4xx 或 5xx,則該then子句不會運行。相反,您需要一個catch處理這種情況的子句。
.then((response) => {
const Swal = require('sweetalert2');
console.log(response.data);
Swal.fire('Great!', 'Password updated successfully', 'success')
}).catch((response) => {
alert('error ', 'password has not been changed !!');
console.log(error);
});
在這種情況下,您可以洗掉try-catch因為它不會捕獲任何錯誤。
或者,您可以await使用 axios 呼叫的結果讓當前catch子句捕獲錯誤。然后你還需要函式是async.
const submitForm = async () => {
let form_data = new FormData();
form_data.append('old_password', formValues.oldpass);
form_data.append('new_password', formValues.newpass);
try {
await axios.put(baseUrl '/change-password/', form_data,
{
headers: {
'Authorization': `Token ${token}`
}
}
).then((response) => {
const Swal = require('sweetalert2');
console.log(response.data);
Swal.fire('Great!', 'Password updated successfully', 'success')
});
} catch (error) {
console.log(error);
alert('error ', 'password has not been changed !!');
}
};
https://axios-http.com/docs/handling_errors
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/460398.html
