Bad Request 400 - Using Fetch API

Asked

Viewed 419 times

0

I’m having trouble accessing my api using POST method. This is my requisition:

function createTool(token, obj) {
  return fetch(`${url}/tools`, {
    method: 'POST',
    headers: {
      Authorization: token,
    },
    body: JSON.stringify(obj),
  })
    .then(async (response) => await response.json());
}

This is the answer from my back-end:

XHRPOSThttp://localhost:3000/tools
[HTTP/1.1 400 Bad Request 17ms]
    error   "Field 'title' doesn't have a default value"

In my console the Back-End returns the execution correctly. However, the insertion object is empty.

Executing (default): INSERT INTO `tools` (`id`) VALUES (DEFAULT);

Where I’m making the mistake of passing values?

  • It seems to me that it is not possible to reproduce the problem only with this information, which database used? What is your schema? How does the back end handle the request? Maybe editing your question with this information will help you with getting an answer, see more on [mcve]

  • 1

    this Exception is coming from sql itself, its table 'tools' has the field 'title' non nullable, is trying to insert null and it is warning that it does not have a default value to fill

  • Every time I had this problem of getting back to the empty object, it was that the object that the back is prepared to receive is not the same as what the front is sending. Like, sometimes the front sends a cnpj field in string, and the back gets in int. Or vice versa. Review your Oos object and their types in relation to the object the back receives and the types. int, has to receive int, string with string, and so on.

1 answer

1

I was able to solve by specifying the file type of the resource in my header.

The requisition went like this:

function createTool(token, tool) {
  return fetch(`${url}/tools`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',u
      Authorization: token,
    }, 
    body: JSON.stringify(tool),
  })
    .then(async (response) => await response.json());
}

Thanks for the tips in the comments.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.