【问题标题】:axios go in catch function instead of then, if status is 302axios 进入 catch 函数而不是 then,如果状态是 302
【发布时间】: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;
    })
}

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

【问题讨论】:

  • 但是为什么您要提供状态为 302 的响应(找到状态,它必须包含 Location 标头,即重定向)?如果您之前创建资源,您可能希望使用状态 201(已创建)。 Read this
  • 您是否尝试在 axios post call 成功时重定向您的应用程序?
  • 不,我只是想得到回应。

标签: node.js mongodb axios


【解决方案1】:

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

【讨论】:

  • 谢谢你这对我有用。 Microsoft 将异步端点的标准设置为返回 202 和 302,因此有时您不能只是将成功状态代码随机更改为 200。
【解决方案2】:

如果您只想通过创建的资源获得响应,您可以使用200 Success201 Created 状态。 如果您想以某种方式处理302 Found,您应该在catch() 部分创建自己的处理程序,并发送Location 标头,因为状态302 Found 意味着:

“您要查找的内容存在但位于不同的位置”

有关此主题的有关 axios 的更多信息,您可以阅读here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2016-02-14
    • 2018-05-28
    • 1970-01-01
    • 2018-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多