How to raise post request with FormData includes attachments in request.json

Hi Team,
I need to raise a request with form data in Request.json
unable to send formdata to request post method throws error

model.js:
  let formData = new FormData();

formData.append("requested_for", apiData.requested_for);
  formData.append("email", apiData.email);
  let jsonObject = {};
formData.forEach((value, key) => {
  jsonObject[key] = value;
});
console.log("jsonObject :", jsonObject)
  let createTicketRes = await client.request.invokeTemplate("createTicket",{ "context": { "requestItemID": requestItemID,"formData":formData}})

Request.json:

    "createTicket": {
        "schema": {
            "protocol": "https",
            "method": "POST",
            "host": "<%= iparam.lightHouseUrl %>",
            "path": "/api/v2/service_catalog/items/<%= context.requestItemID %>",
            "headers": {
                "Authorization": "Basic <%= iparam.lightHouseTokenValue %>",
                "Content-Type": "application/json",
"formData":"<%= context.formData %>"
            },
           
        }
    
    }```

how to convert context.formData to actual formdata in request.json?
is there any workaround?

**Note** : whereas formdata contains attachments also


ERROR`RES::  DOMException: Failed to execute 'postMessage' on 'MessagePort': FormData object could not be cloned.
    at obj.postMessage (https://cdn.freshdev.io/assets/app-client@2.js:6:4992)
    at https://cdn.freshdev.io/assets/app-client@2.js:6:4939
    at new Promise (<anonymous>)
    at obj.handleRequest (https://cdn.freshdev.io/assets/app-client@2.js:6:4850)
    at obj.invokeTemplate (https://cdn.freshdev.io/assets/app-client@2.js:6:22096)
    at formSubmitData (http://localhost:10001/iframe/agent/model.js:10317:73)`

I tried to set Body even it throws error

MODAL.js
   let createTicketRes = await client.request.invokeTemplate("createTicket",{ "context": { "requestItemID":requestItemID}, "body":formData})


REQUESTS.JSON

  "createTicket": {
        "schema": {
            "protocol": "https",
            "method": "POST",
            "host": "<%= iparam.lightHouseUrl %>",
            "path": "/api/v2/service_catalog/items/<%= context.requestItemID %>",
            
            "headers": {
                "Authorization": "Basic <%= iparam.lightHouseTokenValue %>",
                "Content-Type": "multipart/form-data"
            }
        }
    
    }
}

error:

RES:: DOMException: Failed to execute ‘postMessage’ on ‘MessagePort’: FormData object could not be cloned.
at obj.postMessage (https://cdn.freshdev.io/assets/app-client@2.js:6:4992)
at https://cdn.freshdev.io/assets/app-client@2.js:6:4939
at new Promise ()
at obj.handleRequest (https://cdn.freshdev.io/assets/app-client@2.js:6:4850)
at obj.invokeTemplate (https://cdn.freshdev.io/assets/app-client@2.js:6:22096)
at formSubmitData (http://localhost:10001/iframe/agent/model.js:10317:73)

Hi @Deiviya_Sivacoumar,

The form-data is not a documented feature. It might have worked in the Request Method before platform v2.3. With platform v2.3, the Request Method has been enhanced to support only via defined request templates. Form-data is not one of the supported options.

If we have to support form-data, we have to accept it as a new feature request and validate and support it if feasible and prioritized.

Multipart content type is not supported, and attachments cannot be sent via Request Template. So, please find alternative way to work with attachments.

Refer to this post for the supported content types in the Request Method.

@Raviraj Can you take this up as a new feature request? Also, could you please suggest an alternative way to post a request with an attachment?

Hi @Raviraj,
Here is the server.js code which i tried to push formdata with attachments. Please check and let me know where am going wrong

Server.js

type or paste code here
//Create ticket values 
createTickets: async function (option) {
  try {
    console.log('www: ',option.payload)
    let formData = new FormData();
    for (let key in option.payload) {
      if (option.payload.hasOwnProperty(key)) {
        console.log("key ", key);
        // && Array.isArray(option.formData[key])
        if (key === 'attachments[]' ) {
          // for (let file of option.formData[key]) {
          //   let blob = await fetch(file.path).then(r => r.blob());
          //   formData.append(key, blob, file.name);
          // }
          console.log("AS")
        } else {
          formData.append(key, option.payload[key]);
        }
      }
    }
    console.log("Entered Create Ticket,23rq3r23r23R", option)
    let response = await axios.create({
      baseURL: "https://" +option.iparams.lightHouseUrl,
      headers: { "Authorization": "Basic " + option.iparams.lightHouseTokenValue, "Content-Type":"multipart/form-data"},
     
    }).post("/api/v2/service_catalog/items/" + option.requestItemID,formData );
    console.log("Lighthouse: res ", response);

    renderData(null, { "status": response.status, "message": option});
  } catch (err) {
    console.log("Lighthouse: res ", err.response);

    let errorName ="Error in lll "
    console.error(errorName+" : "+JSON.stringify(err.response)+" : ");
    invokeMailNotification(err,option,errorName);
    renderData({ "status": err.response, "message": option.payload}, null);
  }
}, 

Model.js

client.request.invoke("createTickets", { "payload": jsonObject,"requestItemID": requestItemID})
        .then(async function (response){
   console.log("response ", response)
      if(response.status == 200){

ERROR MESSAGE
data: {
message: ‘POST method is not allowed. It should be one of these method(s): GET, HEAD’
}
}

TypeError: Converting circular structure to JSON
→ starting at object with constructor ‘ClientRequest’
| property ‘socket’ → object with constructor ‘TLSSocket’
— property ‘_httpMessage’ closes the circle
at JSON.stringify ()
at Object.createTickets (server.js:4480:46)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
undefined

@Deiviya_Sivacoumar Only GET method is available for Service Item API in Freshservice. I can’t find POST method availability in the documentation.

If it’s an undocumented feature, you would have to check with the Freshservice team to see if it will work as expected. Please create a support ticket for Freshservice to check this.

The first error comes from the API made using Axios.
The second error results from some object being converted into JSON, which has a circular dependency. Please check the same on your code.

@Raviraj here is the documented link of post request in freshservice with attachments
https://api.freshservice.com/v2/#create_ticket

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.