[英]axios go in catch function instead of then, if status is 302
我正在通過創建 function 將數據保存到 mongodb,在成功將數據保存到數據庫后,我正在發送帶有 302 狀態代碼的消息。 但是 axios 進入捕獲 function 而不是 function。並且響應未定義。但是當我在.network 選項卡中看到響應時。我得到了響應。下面是我的代碼。
保存數據在 mongodb
exports.addProject = async (req, res) => {
Project.create(req.body)
.then(function(){
res.status(302).send({message: MESSAGE.PROJECT_ADDED_SUCCESS})
})
.catch(err => handleErrors(res, err));
};
在前端,在 axios 中,同時得到響應
export function addProject(data) {
const token = localStorage.getItem(CONFIG.AUTH_TOKEN);
const url = `${CONFIG.API_BASE_URL}/api/projects`;
axios.post(url, data, { headers:{ Authorization:`${token}`}}).then(function(response){
console.log(response);
return response;
})
.catch(function(response){
console.log(response);
return response;
})
}
您可以使用選項validateStatus
這是默認值
// `validateStatus` defines whether to resolve or reject the promise for a given
// HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
// or `undefined`), the promise will be resolved; otherwise, the promise will be
// rejected.
validateStatus: function (status) {
return status >= 200 && status < 300; // default
}
您可以添加您的自定義,以允許
validateStatus: function (status) {
return status >= 200 && status <= 302
}
如果您只想獲得已創建資源的響應,您可以使用200 Success
或201 Created
狀態。 如果你想以某種方式處理302 Found
,你應該在catch()
部分創建你自己的處理程序並發送Location
header 因為狀態302 Found
意味着:
“您正在尋找的內容存在,但在不同的位置”
有關與 axios 有關的此主題的更多信息,您可以在此處閱讀。
這解決了這個問題。
試試這個例子:
result = await axios.get(url, {
validateStatus: function (status) {
// if this function returns true, exception is not thrown, so
// in simplest case just return true to handle status checks externally.
return true;
}
});
if (result.status === 302) {
// GET YOUR RESPONSE HERE
console.log(result.data);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.