簡體   English   中英

即使在成功完成 Rest API 調用后,Axios 也會發布進入 catch 塊

[英]Axios post entering catch block even after successful Rest API call completion

我的 axios 發布請求未返回 API 在非成功 401 場景中返回的值。 當它成功時它工作正常。

我的重置密碼 API 返回狀態代碼,以及每次調用的消息。 當我使用郵遞員測試其重置密碼的輸出時,給出不正確的當前密碼,我得到

郵遞員輸出:

 statusCode: 401, headers: { ....... ........ }, body: "{"code":"NotAuthorizedException","name":"NotAuthorizedException","message":"Incorrect username or password."}" <--- This is the body output

但是在我的 axios 帖子中,它轉到了 catch 塊:

 await Axios.post(resetAPIUrl, resetParams, config).then(value=> { console.log(`Returned data ----> ${JSON.stringify(value)}`); resolve(value); }).catch(error=>{ console.log(`Failing--->${error}`) reject(error) });

這是我在 Axios 帖子的 catch 塊中遇到的錯誤:

Error: Request failed with status code 401

錯誤原因是正確的。 但是為什么它會進入 catch 塊呢? 它成功地完成了這個過程。 直接從郵遞員調用 API 給了我正確的輸出結構。

攔截器就是答案。 由於 Axios 不會將 200 以外的任何響應視為成功場景,因此可以使用攔截器來捕獲其他響應:

 { Axios.interceptors.request.use(req=>{ console.log(`This is the request ---> ${req.method} ${req.url}`) return req; }) Axios.interceptors.response.use(res => { console.log(`res status ---> ${res.status}`) resolve(res) return res; }, (error)=>{ console.log(`This is the error status ---> ${error.response.status}`) if(error.response.status === 401){ resolve(error.response); } }) await Axios.post(resetAPIUrl, resetParams, config);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM