Posting custom data to an api in new backoffice
h
Has anyone got an example of how to handle data posted from the new backoffice to an api controller? I can get it to post but not sure how to handle/get at the data. I have a method in my workspace that posts some form data
Copy code
async function updatePoll(formdata: FormData) {
  const apiAddress = "/post-question";
  const headers: Headers = new Headers();
    headers.set('Content-Type', 'application/x-www-form-urlencoded');

  const response = await fetch(apiAddress, {
    method: 'POST',
    headers: headers,
    body:     JSON.stringify(Object.fromEntries(formdata))
,
  });
        const data = await response.json();
    if (response.ok) {
        console.log(data);
    }
}
I'm currently sending a string as could not figure out how to handle the formData object in the controller I can hit my controller method and extract the json string from the body, so it definitely all works. Seems a bit hacky, so wondered if anyone else had done something simiar? The data does not come from umbraco, it comes from some custom tables.
Not sure if it's the best approach, but just created a new json string by parsing the formdata and send that to my controller, so I can now serialize it into my model 🙂
My code
Copy code
js
    private async  updatePoll(formdata: FormData) {

        const value = Object.fromEntries(formdata.entries());

        const answers = formdata.getAll("Answers");
        const sort = formdata.getAll("answerssort");
        const ids = formdata.getAll("answersid");
        //construct the answers json array
        let answersString = '[';
        for (var i = 0; i < answers.length; i++) {
            answersString += '{"Id":'+ ids[i] +',"Value":"'+ answers[i] +'","Index":'+ sort[i] +' }';
            if (i < answers.length - 1) {
                answersString += ',';
            }
        }
        answersString +=']';

        //update value
        value.Answers = JSON.parse(answersString);
        const jsonstring = JSON.stringify(value);

        const headers: Headers = new Headers();
        headers.set('Content-Type', 'application/json');

        const response = await fetch("/post-question", {
            method: 'POST',
            headers: headers,
            body:     jsonstring
        ,
            });
            const data = await response.json();
            if (response.ok) {
                //do something with the results
                console.log(data);
            }
        }
    }
8 Views