【发布时间】:2019-04-28 01:30:50
【问题描述】:
我正在使用 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;
})
}
【问题讨论】:
-
但是为什么您要提供状态为 302 的响应(找到状态,它必须包含 Location 标头,即重定向)?如果您之前创建资源,您可能希望使用状态 201(已创建)。 Read this
-
您是否尝试在 axios post call 成功时重定向您的应用程序?
-
不,我只是想得到回应。