Why is my secret recipe payload missing the secret spice?
const form = document.querySelector('form');
const data = new FormData(form);
data.set('spice', 'paprika');
fetch('/bake', { method: 'POST', body: new URLSearchParams(data) });
Reply with what is broken and how you would fix it.
The URLSearchParams constructor doesn’t quite know how to handle a FormData object directly. It expects something it can iterate over as key-value pairs.
If the server expects multipart/form-data, you can just pass the data object directly to the body of the fetch request.
Spot the Bug answer: The FormData object is being converted to URLSearchParams, which does not correctly handle file inputs or complex data structures when sent as a request body.
The fix:
Change 'body: new URLSearchParams(data)' to 'body: data'.
Why:
When sending a POST request with FormData, the body should be the FormData object itself. The browser will then automatically set the ‘Content-Type’ header to ‘multipart/form-data’ and correctly serialize the data, including any files. Using URLSearchParams converts the data into ‘application/x-www-form-urlencoded’ format, which flattens the data and can lead to loss of information or incorrect parsing on the server side, especially for non-string values or files.