chitzui
chitzui

Reputation: 4098

Express body-parser req.body with formdata is empty object

Somehow my req.body is always empty, maybe you have an idea:

here is my server code:

const Express = require('express');
const bodyParser = require('body-parser');

const app = new Express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.post('/save', (req, res) => {
  console.log(req.body)  // => {}
  res.send(req.body);
});

const env = process.env.NODE_ENV || 'production';
app.listen(3000, err => {
   if (err) { return console.error(err); }
   console.info(`Server running on http://localhost:${port} [${env}]`);
});

When I try to send formdata with javascript the req.body is empty:

const data = new FormData(document.querySelector('form'));
console.log(data);  // seems empty already??? FormData{}??
const xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:3000/save');
xhr.send(data);

Same with postman:

postman

I don’t understand this…

Sending x-www-form-urlencoded with postman or raw (application/json) works in postman. But sending the same headers with Formdata in javascript will still result in an empty object…

Upvotes: 16

Views: 39569

Answers (7)

Sachet Subedi
Sachet Subedi

Reputation: 1

For me, the solution was to use express-fileupload. Insted of using multer which i don't like and is complicated to setup, express file upload easily parses form-data.

my code goes:

app.use(
  fileUpload({
    useTempFiles: false,
    tempFileDir: "/tmp/",
    abortOnLimit: true,
    limits: { fileSize: 50 * 1024 * 1024, files: 10 },
    responseOnLimit: "File size limit has been reached",
    uploadTimeout: 10000, // 10 seconds
  })
);

you need to install express-fileupload

Upvotes: 0

sezanzeb
sezanzeb

Reputation: 1139

Use multer, but I'd like to mention that formidable can also be used for this. Ideally this should be an express middleware though.

import formidable, { Fields } from 'formidable';

function getFormData(request: express.Request): Promise<Fields> {
    const form = new formidable.IncomingForm();
    return new Promise((resolve, reject) => {
        form.parse(request, function(error: Error, fields: Fields) {
            if (error !== null) {
                reject(error);
            }

            resolve(fields);
        })
    });
}

app.post('/foo', async (request: express.Request, response: express.Response): Promise<void> => {
    const formData = await getFormData(request);
    // ...
});

Upvotes: 0

Steven Muganwa
Steven Muganwa

Reputation: 480

I had this same problem, I was using the fetch api, sending form data to an node.js/express backend. The problem was that I had set enctype='multipart/form-data' on the form and I was also setting Content-type: multipart/form-data in the fetch Headers. Removing the Content-type from the Headers got everything to work. I got the solution from here => https://github.com/expressjs/multer/issues/411

Upvotes: 1

Rafiq
Rafiq

Reputation: 11535

Express and body parser Version :

"dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1"
  }

app.js:

const express = require('express');
var bodyParser = require('body-parser')

const app = express();

app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
})); 
app.use( bodyParser.json()); 

const baseUrl = '/api/v1/tours';
app.post(baseUrl, (req, res)=>{
    console.log(req.body);
    res.send('Done');
})
//starting server
const port = 3000;
app.listen(port, ()=>{
    console.log(`app running on port ${port}...`);
});

To send raw data please select JSON from the list enter image description here

Upvotes: -2

Akim Kelar
Akim Kelar

Reputation: 635

body-parser is deprecated and isn't a part of Express anymore.

Also, body-parser does not provide the functionality to parse form-data post data.

From the body-parser repository description:

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:

Upvotes: 11

James Lewis
James Lewis

Reputation: 13

From what I understand, the problem may be in the HTML form.

<form action="" method="POST">
 <input type="text" name="foo[bar]">
 <button>Submit</button>
</form>

Then in the server code it may look something like this.

 app.post('/save', (req, res) => {
 console.log(req.body.foo)  // => {}
 res.send(req.body.foo);
});

Again, this post is older so you've probably already fixed it.

Upvotes: 1

Sumit M
Sumit M

Reputation: 650

To log every field in formData

let myForm = document.getElementById('myForm');
formData = new FormData(myForm);

for (let [key, value] of formData.entries()) { 
  console.log(key, value);
}

Fiddle - https://jsfiddle.net/thesumit67/j4znhxa5/1/

To handle it via express use multer. Here is an example - https://www.npmjs.com/package/multer

Make sure to add enctype="multipart/form-data" on form element. Otherwise Multer will ignore it.

let multer = require('multer');
let upload = multer();

app.post('/save', upload.fields([]), (req, res) => {
  console.log( req.body );
  console.log( req.files );
  res.sendStatus(200);
});

Upvotes: 23

Related Questions