RinMori
RinMori

Reputation: 61

Axios does not return the error in the frontend?

I create a server on NodeJs by using Express and MongoDB (Mongoose) to create REST API after that I connect that API to my Frontend (ReactJS). the problem is that when I send post request from Axios, but on error (Duplicate Key) they not respond to catch and give a response on .then like that {data: "You Cannot Add Duplicate Link", status: 200, statusText: "OK", headers: Object, config: Object…}

FrontEnd:

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 });
  });
}

BackEnd:

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") : ""
    );
 };

Upvotes: 0

Views: 324

Answers (1)

Shams Nahid
Shams Nahid

Reputation: 6559

Make sure you are sending error status while send the response from the server.

The standard way to send a response is by using a status code.

Like,

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

For error in server, you should use the following response,

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

Your final backend code should,

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") : ""
    );
 };

You may want to change the suitable status code.

For details, check the documentation.

Also fix your front end setState() method, as suggested in the comments.

Upvotes: 2

Related Questions