1

I am using Axios to send POST requests to my Express Application. I normally have a values object containing the inputs and when I send this values object to the backend, everything is working fine and I can grab these values from req.body. I tried to convert this values object to a FormData object.

let formData = new FormData();

Object.keys(values).map((key: string) => {
     formData.append(key, values[key]);
});

I also logged the formData object by iterating through its entries and it's filled with the content of the values object. However, when I make this POST request, req.body comes as an empty object. After facing this problem, I've tried some solutions in the internet which mostly suggested adding the below lines to 'app.js' file in the Express Application. Sadly this didn't help as well.

// app.use(express.json());                                         
// app.use(express.urlencoded({ extended: false }));

app.use(bodyParser.json());                                         
app.use(bodyParser.urlencoded({ extended: true }));

I also tried placing the header { 'content-type': 'application/json' } in my post request but again couldn't make it.

I'd be glad if someone could help me with this one, thank you.

atunays
  • 23
  • 2
  • Do you have any console log errors? – awran5 Apr 02 '20 at 14:42
  • No, not at all. Works fine except that I receive req.body as {} when I send 'formData' instead of 'values'. – atunays Apr 02 '20 at 14:45
  • I guess the problem is that FormData set the content type of your Fetch API request to `multipart/form-data` and body-parser [does not handle multipart bodies](https://www.npmjs.com/package/body-parser). Try other modules like busboy, formidable, multer. – awran5 Apr 02 '20 at 15:14
  • Check [here](https://stackoverflow.com/questions/41774334/fetch-post-with-formdata-is-empty-in-express-js-route) or [here](https://stackoverflow.com/questions/37630419/how-to-handle-formdata-from-express-4) – awran5 Apr 02 '20 at 15:18
  • Sir, Thank you a million times! Been trying to deal with this problem since hours. You made my day! – atunays Apr 02 '20 at 15:24

0 Answers0