0

I am posting some details using fetch API which are stored in a JavaScript Object. Inside this object there are three fields

  1. data_items : [Array]
  2. exporter_app : "String"
  3. step : "String" After I am posting the data I am getting an error 500, and when I am viewing the payload in the network tab of chrome all the data is there except the file. The file field has an empty object in it - file:{} This Request Data is in this format:
{
   "data_items":[
   {
   "name": "Trevor",
   "phone_number": "86545352556",
   "email_id": "trevor@test.com"
   "file":File
   },
   {
   "name": "Trevor",
   "phone_number": "86545352556",
   "email_id": "trevor@test.com"
   "file":File
   }
    ],
   "exporter_app":"17",
   "step:"step_4"
   }

There can be "n" number of objects in "data_items".

//This the handleRequest function:
const handleRequest = async (url, options) => {
  const response = await fetch(url, options);
  if (response.status === 401) {
    window.location.assign(API_HOME_URL);
    return null;
  }
  if (response.status === 422) {
    const data = await response.json();
    // console.log(data);
  }
  return response;
};

//Initially i was using this function to post data:
export const POSTFORMDATA = async (url, formData) => {
  const fullUrl = `${API_BASE_URL}${url}`;
  const options = {
    method: "POST",
    headers: {
      "X-CSRFToken": sessionStorage.getItem("csrf_token"),
      authorization: `Bearer ${sessionStorage.getItem("auth_token")}`,
    },
    body: formData,
  };

  return handleRequest(fullUrl, options);
};

//Then I modified it to this function:
export const POSTFORMDATA = async (url, data) => {

  const fullUrl = `${API_BASE_URL}${url}`;
  const formData = new FormData();

  if (data.data_items && Array.isArray(data.data_items)) {

    data.data_items.forEach((item, index) => {
      const itemFormData = new FormData();
      Object.entries(item).forEach(([key, value]) => {
        if (key === "file" && value instanceof File) {
          itemFormData.append(key, value, value.name);
          console.log(key, value, value.name);
        } else {
          itemFormData.append(key, value);
        }
      });
      formData.append(
        `data_items[${index}]`,
        JSON.stringify(Object.fromEntries(itemFormData.entries()))
      );
    });
  }

  formData.append("exporter_app", data.exporter_app);
  formData.append("step", data.step);

  const options = {
    method: "POST",
    headers: {
      "X-CSRFToken": `${sessionStorage.getItem("csrf_token")}`,
      authorization: `Bearer ${sessionStorage.getItem("auth_token")}`,
    },
    body: formData,
  };

  return handleRequest(fullUrl, options);
};
//Both of them gave me the same results- file:{}

Payload :

   {
      "data_items":[
        {
        "name": "Trevor",
        "phone_number": "86545352556",
        "email_id": "trevor@test.com"
        "file":{}
    },
    {
        "name": "Trevor",
        "phone_number": "86545352556",
        "email_id": "trevor@test.com"
        "file":{}
    }
        ],
        "exporter_app":"17",
        "step:"step_4"
    }
  • 2
    You can't post a file object as part of some JSON structure. You have to post it as part of a multipart mime post body. – Pointy Jul 19 '23 at 14:30

0 Answers0