uploading array of multiple files with react axios

26 views Asked by At

i am trying to submit a post request to a custom api that i don't control, in the documentation of the api this is the request body structure

{
  "addServiceReq": {
    "servicesName": "string",
    "servicesNameEn": "string",
    "servicesDescriptions": "string",
    "servicesDescriptionsEn": "string",
    "servicesPrice": 0,
    "servicesTypeId": 0,
    "extraServices": "string"
  },
  "serviceImages": [
    "string"
  ]
}

in postamn my request works fine where i'm uploading two image files to serviceImages , additionally extraServices is supposed to be an array in json structure like

      [
{
            "extraName":"string",
            "extraNameEn":"string",
            "extraDescriptions":"string",
            "extraDescriptionsEn":"string",
            "extraPrice":0
        }
 ] 

my problem is , i cant seem to find which of this two fields is causing a 403 forbidden, this is how i am handling my code

 const handleSubmit = async (e) => {
  e.preventDefault();
  try {
    const extraServicesWithParsedPrices = formData.extraServices.map((service) => ({
      ...service,
      extraPrice: parseInt(service.extraPrice),
    }));
    const extraServicesString = JSON.stringify(extraServicesWithParsedPrices);


    const addServiceReq = {
      servicesName: formData.servicesName,
      servicesNameEn: formData.servicesNameEn,
      servicesDescriptions: formData.servicesDescriptions,
      servicesDescriptionsEn: formData.servicesDescriptionsEn,
      servicesPrice: parseInt(formData.servicesPrice),
      servicesTypeId:parseInt(TypeId),

      extraServices: extraServicesString
    };
     
    const formPayload = new FormData();
    formPayload.append('addServiceReq', JSON.stringify(addServiceReq));  
  
    formData.serviceImages.forEach((file, index) => {
      formPayload.append(`serviceImages`, file); 
    });

    const response = await axiosInstance.post(
      'Api-url',
      formPayload,
      {
        headers: {
          Authorization: `Bearer ${accessToken}`,
          'Content-Type': 'multipart/form-data'
        }
      }
    );

both serviceImages and extraServices are set as empty arrays initially in state, is the problem how i'm converting extraServices to json twice in the request , or how i'm handling my array of images uploading ? i appreciate any help

here's how the current request payload looks like

addServiceReq: {"servicesName":"aa","servicesNameEn":"aaa","servicesDescriptions":"aa","servicesDescriptionsEn":"a","servicesPrice":120,"servicesTypeId":1,"extraServices":"[{\"extraName\":\"aa\",\"extraNameEn\":\"aa\",\"extraDescriptions\":\"aa\",\"extraDescriptionsEn\":\"aa\",\"extraPrice\":120}]"}
serviceImages: (binary)

i apologize if similar questions to this have been answered before, i checked many i just can't seem to find an answer to my case.

0

There are 0 answers