2

I have this POST api in swagger: enter image description here
enter image description here

when I send request in swagger it returns 200 status code

I also try the exact same request in postman and it also returns 200 status code so everything is good: enter image description here

but when it comes to js, I send the exact same request in js but server returns 400 status code with message: "title can not be empty"
but I'm sure that I'm sending title correctly.
this is my code:

export const createFood = async (title, description, file, price) => {
  try {
    const { data } = await client.post(`/Restaurant/food`, {
      title,
      description,
      "file.form_file": file,
      price: parseFloat(price),
    });

    return data;
  } catch (error) {
    return error.response.data;
  }
};

this is browser network log:
enter image description here
enter image description here

what am I doing wrong?

Alireza
  • 23
  • 5
  • Your postman and swagger are saying your request is going as form-data but your js code is like an object. Are you doing manipulations in `client.post()` method. Try converting that request object to form-data and test. – mc-user Apr 27 '22 at 15:17

1 Answers1

2

In js, you are sending your data as an object. but you should send it as form-data like this:

export const createFood = async (title, description, file, price) => {
  const formData = new FormData();

  formData.append("title", title);
  formData.append("description", description);
  formData.append("file.form_file", file);
  formData.append("price", parseFloat(price));

  try {
    const { data } = await client.post(`/Restaurant/food`, formData);

    return data;
  } catch (error) {
    return error.response.data;
  }
};
Mahdi Dahouei
  • 1,588
  • 2
  • 12
  • 32