Getting 422 ERROR when sending a POST request

572 Views Asked by At

Here's the code I use:

  const url = new URL("https://api.chec.io/v1/products");
  const headers = {
    "X-Authorization": `${process.env.NEXT_PUBLIC_CHEC_PUBLIC_KEY_SECRET}`,
    "Accept": "application/json",
    "Content-Type": "application/json",
  };

  fetch(url, {
    method: "POST",
    headers: headers,
    body: JSON.stringify({
      name: 'Samsung', 
      price: '345',
    }),
  })
    .then((response) => response.json())
    .then((data) => console.log(data))
    .catch((err) => console.log(err));

I am trying to send a POST request to create a product for an e-commerce project by using Commercejs API. However, the result I get is a 422 ERROR, which by a little research tells:

* Error 422 is an HTTP code that tells you that the server can't process your request, although it understands it. The full name of the error code is 422 “unprocessable entity.” In a nutshell, the error means that you're making a request the server understands, but it can't process it.*

There is another post that doesn't seems to work in my case: 400 vs 422 response to POST of data

Here's the docs about creating a product(which is what I try to do): https://commercejs.com/docs/api/#create-product

1

There are 1 best solutions below

0
Vasile Midrigan On

The problem was the format of the data I was sending. I was supposed to send it in this format (the problem the body), I guess I was confused thinking that the curly braces of the body actually means an object which I suppose now this is not wright actually, the curly braces wraps the data you send to the server, so in my case I was not sending an object product {} which is required by docs, but instead I was sending name: 'Samsung' and price: 345, which was not acceptable by the server. Anyway, thanks for suggestions. Next time would be better to pay attention to what the server expects and what we are actually sending in case we get 422 ERROR.

fetch(url, {
    method: "POST",
    headers: headers,
    body: JSON.stringify({
      product: {
        name: 'Iphone', 
        price: 4535,
      }
    }),
 })