Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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--
like image 891
Mad Eddie Avatar asked Nov 27 '25 04:11

Mad Eddie


1 Answers

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.

like image 59
yongju lee Avatar answered Nov 30 '25 00:11

yongju lee