Set Form-Data on fetch api

How can I set the form-data of an api url? I need to do a post that has a body which uses a form-data

Are you calling the JA API from an external system or writing a CloudCode task to call an API? If the former, the details here are dependent on your programming language but you can surely find loads of results by googling something like “[language e.g. Java] POST request”

If the latter, here’s an example of making a post request to the lock user endpoint:

/**
 * @param {DB.user} user
 * @param {any} backend
 */
async function lockUser(user) {
    var url = this.backend.url + '/users/' + user.id + '/lock';
    let response = await fetch(url, {
        method: 'POST',
        headers: {
            Authorization: this.backend.authorization,
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({"wipe": false}) // this is the form data
    });
    if(!response.ok) {
        console.log("Response[" + response.statusText + "] indicates failure.  See below")
        throw new Error(response.statusText);
    } else {
        console.log("Success!");
    }
}
1 Like

Hi @sisa-zaza

If you want to send form-data from JourneyApps to some other system then you will need to use CloudCode. Something like this should work to emulate the request that a form would make

    let form = new URLSearchParams();
    form.append("from", "Tielman");
    form.append("to", "Forums");
    
    let url = 'https://some-domain.com/form_data_route';
    let config = {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
         body: form
    }

    let response = await fetch(url, config)
    console.log(response);

If you want to post formData from a different system to JourneyApps then you do have some options as well, however it is not currently possible to HTTP POST form data directly to JourneyApps (i.e. you cannot point a HTML form action to a JourneyApps endpoint.

What you can do is the following.

  1. Use a GET method on your HTML Form and point the action to a custom CC Webtask URL
  • when you use a GET method on a HTML form, the form values get converted into URL params and these will then be accessible in your CC webtask in the GET function as the params variable
  1. POST the formData as JSON instead - what is involved in this depends on the technologies you are using to serve and populate the form
1 Like