0

I am sending form data with a basic POST request:

const formData = new FormData();
formData.append('id', '123');
const res = await fetch('./handler', { method: 'POST', body: formData });
const json = await res.json();

handler.js

export default async function handler(req, res) {
 console.log(req.body.id);
 ...
}

The code above will log undefined. When logging req.body the result is something that definitely needs decoding:

------WebKitFormBoundary
Content-Disposition: form-data; name="id"

123
------WebKitFormBoundary --

How do I read the data passed?

sdvnksv
  • 9,350
  • 18
  • 56
  • 108

3 Answers3

0

Try using formidable

in handler.js

import formidable from 'formidable';

export default async function handler(req, res) {
  const form = formidable();

  form.parse(req, (err, fields) => {
    if (err) return console.error(err);

    console.log(fields.id);
  });
}
  • Don't forget to disable Next.js built-in body parser if you're using Next.js: https://stackoverflow.com/questions/60020241/next-js-file-upload-via-api-routes-formidable-not-working. – sdvnksv Mar 09 '23 at 21:29
0

Good afternooon,

You could try taking a look at this post and find out how to decode formdata.

However if you're intending to run this code in a browser import libraries is a hassle. In the event that the API is capable of responding with JSON, then I would recommend that since JS handles this without too much hassle.

You can try to request the data as JSON by adding the Accept header:

const requestOptions = {
  method: "POST",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded", // what you're sending
    "Accept": "application/json" // what you expect back
  }
}

You could alternatively also just send JSON ()

const formData = new FormData();
formData.append('id', '123');

// would become
const reqBody = { id: 123 }
TiesDO
  • 31
  • 8
0

I believe you can use req.body.id to get the outcome of '123'. Fetch treats form data as JSON IIRC.

Geoff
  • 353
  • 3
  • 19