axios 不会return 前端报错?

Axios does not return the error in the frontend?

我通过使用 Express 和 MongoDB (Mongoose) 创建 REST API 在 NodeJs 上创建一个服务器,然后我将 API 连接到我的前端 (ReactJS)。问题是,当我从 Axios 发送 post 请求时,但出现错误(重复键)时,他们没有响应 catch 并在 .then 上做出响应,就像那样 {data: "You Cannot Add Duplicate Link", status: 200, statusText: "OK", headers: Object, config: Object…}

前端:

axios
  .post(`${SERVER}`, post) // Here Post is an object
  .then(async res => {
    await this.setState({ host: res.data._id });
  })
  .then(() => this.setState({ loading: false }))
  .catch(async error => {
    await this.setState({ error: error.res });
  });
}

后端:

const post_link_with_id = async (req, res) => {
  await models
   .create({
     // Objects like obj_key: req.body.obj_model
    })
   .then(result => res.send(result))
   .catch(err =>
      err.code === 11000 ? res.send("You Cannot Add Duplicate Link") : ""
    );
 };

确保在发送来自服务器的响应时发送 error status

发送响应的标准方式是使用状态代码。

喜欢,

res.status(statusCode).send(responseMessage);

对于服务器错误,您应该使用以下响应,

err.code === 11000 ? res.status(404).send("You Cannot Add Duplicate Link") : "";

你的最终后端代码应该,

const post_link_with_id = async (req, res) => {
  await models
   .create({
     // Objects like obj_key: req.body.obj_model
    })
   .then(result => res.send(result))
   .catch(err =>
      err.code === 11000 ? res.status(400).send("You Cannot Add Duplicate Link") : ""
    );
 };

您可能想要更改合适的状态代码。

有关详细信息,请查看 documentation

同时按照评论中的建议修复您的前端 setState() 方法。