node.js - axios 进入 catch 函数而不是 then,如果状态是 302
问题描述
我正在使用 create 函数将数据保存到 mongodb,成功将数据保存到数据库后,我正在发送带有 302 状态码的消息。但是 axios 进入 catch 函数而不是 then 函数。并且响应未定义。但是当我在网络选项卡中看到响应时。我得到了响应。下面是我的代码。
在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
}
推荐阅读
- python - 如何在 Python 中录制音频?
- javascript - 为什么我们应该更喜欢 document.visibilityState 而不是 document.hidden?
- java - JavaFX一键切换不同场景
- jquery - 角度扫描仪检测 2+
- laravel - Laravel 分页不能与查询一起使用
- java - Java - 未使用类构造函数中使用的变量
- javascript - 条件为真时如何增加变量
- tfs - 尝试导入工作项类型定义时出现 ProvisioningImportEventsCallback 错误
- complex-event-processing - 使用外部窗口时间戳调试 Siddhi 流查询
- c# - angular 4下载pdf出来空白