Skip to content

Instantly share code, notes, and snippets.

@PUUZOO
Created February 14, 2022 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PUUZOO/7b3e01904dace66130de999a560fe8aa to your computer and use it in GitHub Desktop.
Save PUUZOO/7b3e01904dace66130de999a560fe8aa to your computer and use it in GitHub Desktop.
NextJS, fetch, multipart/form-data, missing boundary

I've faced with issue while proxy http request with multipart form data by NextJS. I have to send file from a client fide to next js, after that - to FastApi service.

The problem was:

 fetch("https://127.0.0.1:3000/api/newfile", {
   method: "POST",
   headers: { "Content-Type": "multipart/form-data" },
   body: new FormData(form)
 });

headers request: "Content-Type: multipart/form-data"

In order for NextJS API to parse the file, you need a header with boundary

Something like this:

multipart/form-data; boundary=----< generate boundary >

For a long time I could not figure out how to get it. There is an exit. It is necessary not to fill in "Content-Type". And then the browser itself will generate this header by passing the form-data.

For example:

fetch("https://127.0.0.1:3000/api/newfile", {
   method: "POST",
   headers: {},
   body: new FormData(form)
 });

I also noticed that the problem concerns fetch

When I used XMLHttpRequest I didn't face such problem.

Further, the header can easily be passed further to FastAPI

in API:

req.headers["content-type"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment