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