0

I'm trying to send a application/x-www-form-urlencoded form through fetch.

My issue is that the format of the sent data is invalid like follows:

  "FormData {
  [Symbol(state)]: [
    {
      name: '------WebKitFormBoundaryhPzR6LljgR6oqP3V\r\n' +
        'Content-Disposition: form-data; name',
      value: '"_id"\r\n' +
        '\r\n' +
        '2\r\n' +
        '------WebKitFormBoundaryhPzR6LljgR6oqP3V\r\n' +
        'Content-Disposition: form-data; name="zied"\r\n' +
        '\r\n' +
        'here I am\r\n' +
        '------WebKitFormBoundaryhPzR6LljgR6oqP3V--\r\n'
    }
  ]
}"

Here's the code that sends it:

function startWithTemplate(event) {
    const id = event.detail?._id;
    const formData = new FormData();
    formData.append('_id', id)
    formData.append('zied', "here I am")
    fetch('?/template', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: formData
    })
        .then(response => {
            console.log('Response:', response);
        })
        .catch(error => {
                console.error('Error:', error);
            });
}

So I created a <form> and tried to send data through it, and the format is completely different:

<form action='?/template' method='post'>
    <input type='hidden' name='_id' value='2'>
    <input type='hidden' name='zied' value='kidding'>
    <button type='submit' >Send</button>
</form>

sends:

FormData {
  [Symbol(state)]: [ { name: '_id', value: '2' }, { name: 'zied', value: 'kidding' } ]
}

Checking the payload source, I found it was : "_id=2&zied=kidding", so I'm able to work around this by typing my values without using the FromData object, but I'd like to be able to handle more complex cases too

Phil
  • 157,677
  • 23
  • 242
  • 245
Zied Hamdi
  • 2,400
  • 1
  • 25
  • 40
  • 1
    Simple, use `URLSearchParams` instead of `FormData`... `fetch('?/template', { method: 'POST', body: new URLSearchParams({ _id: id, zied: 'here I am' }) })` – Phil May 11 '23 at 04:04

0 Answers0