0

I have always sent files along with form data by having the action attribute and multipart enctypes to my html forms. Recently I needed to use fetch to send a form and used the new FormData() can read all my fields and file of a given html form. But on the nodejs end, req.files returns null. When I use form action attribute, it works perfectly.

Client End

let formData = new FormData(document.getElementById('additem'));
let response = await fetch(`${window.location.href}/inventory`, {
            method: "POST",
            body: formData
        });

On the server end I am just using express-bodyparser (which is default now) and am trying to access the files with req.files; I know I can use multer or formidable but I was wondering if there's a way to make it work with what I have atm. Thanks.

sakib11
  • 496
  • 1
  • 5
  • 20
  • The body parser dosn't handle multipart uploads for file uploads. https://stackoverflow.com/a/23118138/5781499 – Marc Feb 26 '20 at 00:14

2 Answers2

1

On the server end I am just using express-bodyparser (which is default now) and am trying to access the files with req.files; I know I can use multer or formidable but I was wondering if there's a way to make it work with what I have atm.

No, there isn't. FormData objects generate multipart bodies.

See the documentation for body parser

This does not handle multipart bodies, due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules:

  • busboy and connect-busboy
  • multiparty and connect-multiparty
  • formidable
  • multer
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
-1

where are your Content-Type if you are going to send a file you need to specified on them headers, by default the content-type is application/json

there is good example at the Mozilla Docs: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Ernesto
  • 3,944
  • 1
  • 14
  • 29
  • 1
    `fetch` will automatically set the correct Content-Type when passed a `FormData` object. You **can't** set the Content-Type for a FormData object manually because you don't know what value the mandatory `boundary` parameter needs to have. – Quentin Feb 25 '20 at 23:08
  • Oh! thats right, then how come you are having this issue‍♀️ just tell me to paste the code so you can do copy/paste of it – Ernesto Feb 26 '20 at 00:13
  • Yeah. I've read that it can cause issues if you define content type with formData. It's something to do with setting boundaries. – sakib11 Feb 26 '20 at 09:21
  • @Ernesto — They are having the issue because they are using body-parser which doesn't support multipart requests. – Quentin Feb 26 '20 at 09:36