alizoubair
alizoubair

Reputation: 47

400 bad request with ReactJs

I'm trying to make a post request to the server,but it returns 400 error. :enter image description here this is react function

const handleSubmit = () => {
  const bookInstanceObject = {
    imprint: imprint,
  };

  axios
    .post('http://localhost:3001/catalog/bookinstance/create', bookInstanceObject)
    .then(res => {
      console.log(res.data);
    })
    .catch(error => {
      console.log(error);
    });
};

and this is the server side:

router.post('/bookinstance/create', (request, response, next) => {
  const body = request.body;

  const bookInstance = new BookInstance({
    imprint: body.title,
  });

  bookInstance
    .save()
    .then(savedBook => {
      response.json(savedBook.toJSON());
    })
    .catch(error => next(error));
});

any idea ?

Upvotes: 0

Views: 1931

Answers (1)

Wesley Williams
Wesley Williams

Reputation: 326

What I think is happening

The front end's handleSubmit function is POSTing to /catalog/bookinstance/create, while the server is expecting it to come to /bookinstance/create.

Simple typo, easy to miss when your stressing over it not working.

How to fix?

Change the URLs to match.

Either:
change the front-end's POST url to /bookinstance/create,
or:
change the server's expected route to router.post('/catalog/bookinstance/create',

Why is it a GET in the error log?

I don't know but I suspect that this error is about a GET request somewhere else in your code.

Please let us know in the comments if the error goes away with this fix. (Assuming my fix works)

Upvotes: 1

Related Questions