Search code examples
sveltesveltekit

Sveltekit unable to read data from POST formdata


Just trying the below in Sveltekit (3.44) but the console always outputs:

Got data FormData {}

The request is simply (made via Postman):

curl --request POST \
  --url http://localhost:3000/todos.json \
  --header 'Content-Type: multipart/form-data; boundary=---011000010111000001101001' \
  --form test=hello

Code: src/routes/todos/index.json.ts

export const post: RequestHandler = async (request) => {
    const data = await request.request.formData();
    console.log('Got data', data);
    return {
        status: 200,
        body: 'text'
    }
}

Othen than destructuring and cleaning up this code - why is formData empty ?

NB When setting the data line to await request.request.text() I receive (which shows I am receiving data):

Got data --X-INSOMNIA-BOUNDARY
Content-Disposition: form-data; name="test"

hello
--X-INSOMNIA-BOUNDARY--

Solution

  • This is a known one: https://github.com/sveltejs/kit/issues/4198 This isn't a bug, it's just hard to log the form data, and make use of it. As suggested in the link, use the following if you really wish to log it in the console:

    const body = await event.request.formData();
    
    // to get everything
    console.log(...body); // ["name", "Rich Harris"] ["hobbies", "svelte"], ["hobbies", "journalism"]
    
    // if you know you don't have duplicates
    console.log(Object.fromEntries(body)); // { name: "Rich Harris", hobbies: "journalism" }
    

    I haven't had any problem using await request.json(), except for when I had to implement file uploads to the API. It gives me a huge headache, and I always end up using the S3 bucket, or make a special API for this with Python, or Express.js.