0

I have an issue with POST requests, that it always returns an empty object if I choose form-data as a body type, it works only when I choose raw, but I need to send form-data to send some files.

Here's my index.js file:

const express = require('express');

const app = express();

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

app.post('/', (req, res) => {
    res.json(req.body);
});

app.listen(5000, () => console.log('Up & Running'));

I found already some solutions like this, and more, but none of them worked out for me.

here's a screenshot from the postman.

Postman, returns an empty object on form-data

as you can see, it returns an empty object here, regardless of ant data that I've sent.

however, if I choose body raw it works fine. Postman, returns the request body on body raw

Has anybody solved this problem before?

  • If you're using the `form-data` content-type, then you need Express middleware that understands that content-type and will read it, parse it and put the results into `req.body` or `req.something`. The server-side code you show so far ONLY handles the content-type of `application/x-www-form-urlencoded` which you are not using. If you can use that content-type, then switch to that and your existing server code will work with that. – jfriend00 Apr 05 '22 at 23:08
  • Here's a discussion of choosing [application/x-www-form-urlencoded vs multipart-form-data](https://stackoverflow.com/questions/4007969/application-x-www-form-urlencoded-or-multipart-form-data). In general, if you just have regular form data, then use either `application/x-www-form-urlencoded` or `application/json`. It is generally the uploading of files that causes people to have to use `multipart/form-data` and you would need middleware such as `multer` that knows how to handle that. – jfriend00 Apr 05 '22 at 23:09
  • I think my answer to the similar question can help you get a hint, check it [here](https://stackoverflow.com/questions/71617579/node-js-req-body-undefined-in-form-data-content-type/71618021#71618021) – taipei Apr 06 '22 at 09:05

0 Answers0