Reactjs React.js:获取错误消息,尽管http响应为400
我有一个场景,在这个场景中,如果我在DB中保存一个重复的记录,模态应该显示准确的错误消息 使用axios发布请求:Reactjs React.js:获取错误消息,尽管http响应为400,reactjs,post,Reactjs,Post,我有一个场景,在这个场景中,如果我在DB中保存一个重复的记录,模态应该显示准确的错误消息 使用axios发布请求: saveBankMaintenance(optionsBrstn){ return axios.post(`${API_URL_SAVE_BANK_MAINTENANCE}`, [optionsBrstn] ) 我使用以下方式调用此POST请求: const saveBrstn = useCallback(() =>
saveBankMaintenance(optionsBrstn){
return axios.post(`${API_URL_SAVE_BANK_MAINTENANCE}`,
[optionsBrstn]
)
我使用以下方式调用此POST请求:
const saveBrstn = useCallback(() => {
ClientMaintenanceService.saveBankMaintenance(optionsBrstn)
.then((response) => {
if(response.data.success === "Success"){
setShowBrstnSaveSuccessModal(true);
setShowBrstnSaveFailedModal(false);
}
}).catch((err) => {
setShowBrstnSaveSuccessModal(false);
setShowBrstnSaveFailedModal(true);
})
});
如果保存成功,则可以保存
但是,当它失败时,它会直接进入catch块,并且我无法在状态上设置错误消息
有没有一种方法可以让我获得包含错误消息的json响应以及http状态响应400
TIA您可以在response属性的error对象中获取响应数据 试试这个
const saveBrstn = useCallback(() => {
ClientMaintenanceService.saveBankMaintenance(optionsBrstn)
.then((response) => {
if (response.data.success === "Success") {
setShowBrstnSaveSuccessModal(true);
setShowBrstnSaveFailedModal(false);
}
}).catch((err) => {
console.log(err.response.data); // you can get the response like this
console.log(err.response.status); // status code of the request
})
});
设置错误状态的功能在哪里?您可以在catch块中调用该函数。工作得非常好!不知道这个,谢谢分享。