How to parse FormData of request in Node.js + Express with sample codes

How to parse FormData of request in Node.js with sample codes.

This article explains how to do this with code examples.

Wrong way to parse FormData

FormData cannot be received by the way below.

Client side : Wrong code for sending request with FormData

/// Create FormData
const formData = new FormData();
formData('message', 'blah blah blah');

/// Send request to Node.js (+Express)
fetch('/api/echo', {
  method: 'POST',
  body: formData
    /// ^ Send FormData
}.then(async (response)=>{
  const result = await response.json();
  console.log('result : ', result)
}).catch((err)=>{
  console.error(err);
});

Node side : Wrong code for parsing FormData .

const express = require("express");
const router = express.Router();

router.post('/api/echo', async (req, res)=>{
  /// Wrong way!!
  const message = req.body.message;
  console.log(message)
    /// => undefined

  res.status(200).json([message]);
});

FormData in a request sent from the client side is not parsed by Node.js or Express.js. This means that FormData parameters cannot be referenced from request.body.

The above code is wrong so not working.

Install express-formidable module

For parsing FormData in Node.js…

A Module for parsing FormData must be installed.

Here is how to do it using the express-formidable module.

npm : https://www.npmjs.com/package/express-formidable

Install express-formidable via npm :

$ npm install express-formidable

There are many more FormData parsing modules that can be found if you look for them. For example, ortexx / express-form-data , expressjs / multer, etc.

But express-formidable is simple and easy to use.

So this module is also recommended.

Correct way to parse FormData

Now let’s parse FormDat by using express-formidable.

Client side : Correct code for sending request with FormData :

/// Create FormData
const formData = new FormData();
formData('message', 'blah blah blah');

/// Send request to Node.js (+Express)
fetch('/api/echo', {
  method: 'POST',
  body: formData
    /// ^ Send FormData
}.then(async (response)=>{
  const result = await response.json();
  console.log('result : ', result)
}).catch((err)=>{
  console.error(err);
});

Node side : Correct code :

const express = require("express");
const router = express.Router();

router.post('/api/echo', async (req, res)=>{
  /// Correct way
  const message = req.fields.message;;
  console.log(message)
    /// => blah blah blah

  res.status(200).json([message]);
});

The parsed FormData can be referenced from the following two.

  • request.fields => contains non-file fields
  • request.files => contains files

So useful to parse and retrieve FormData 🙂

Below articles may be helpful for you.

Good luck 👍

Leave a Reply