首页 > 解决方案 > 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;
    })
}

请告诉我如何在 axios 请求中获得响应然后运行。下面是附加的错误图像。错误图像

标签: node.jsmongodbaxios

解决方案


您可以使用该选项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
}

推荐阅读