DEV Community

Cover image for Creating your own ExpressJS from scratch (Part 6) - Creating a body-parser middleware
Wesley Miranda
Wesley Miranda

Posted on

Creating your own ExpressJS from scratch (Part 6) - Creating a body-parser middleware

I have not created tutorials for our Framework for a while, but It's time to return.

Understanding and Creating a Custom Body-Parser Middleware

In this tutorial, we'll dive into the creation of a custom body-parser middleware for our web framework. Before we get into the code, let's understand why this middleware is essential.


Why a Body-Parser Middleware?

The body-parser middleware is a crucial component in web applications as it allows us to transform incoming data streams from HTTP requests into accessible JavaScript objects. Understanding and creating a custom body-parser middleware is fundamental to handling incoming data effectively.


Creating the Middleware

src/body-parser.js

const BodyParser = async (req, res, next) => {
  // (1)
  let body = []

  for await (const chunk of req) {
    body.push(chunk)
  }

// (2)
  body = Buffer.concat(body).toString()

// (3)
  if (req.headers['content-type'] === 'application/json') {
    req.body = JSON.parse(body)
  }
  else if (req.headers['content-type'] === 'application/x-www-form-urlencoded') {
    let params = new URLSearchParams(body)
    let entries = params.entries();
    req.body = Object.fromEntries(entries)
  }

  next()
}

module.exports = BodyParser

Enter fullscreen mode Exit fullscreen mode

From the code sessions above

We already know how to create middleware for our Framework, It has the same middleware definition. if you don't know, please take a look at the previous tutorials.

1 - We are reading and storing the Stream object from the request.

2 - Converting the Stream object to a String

3 - Depending on the content-type we have to convert the String to a Javascript Object.


Using the Custom Middleware

Now we have to import our middleware and use it for all requests.

index.js

const BodyParser = require('./src/body-parser')

app.useAll(BodyParser)

app.post('/body-parser', (req, res) => {
    res.send(`name: ${req.body.name}, age: ${req.body.age}`)
})

Enter fullscreen mode Exit fullscreen mode

Testing the Middleware

If you make a POST request to the endpoint /body-parser with a JSON body like this:

{
    "name": "Wesley Miranda",
    "age": 28
}
Enter fullscreen mode Exit fullscreen mode

You will receive the following response:

name: Wesley Miranda, age: 28
Enter fullscreen mode Exit fullscreen mode

You can see here how the code is looking.

In the next tutorials, we are going to create the cors and multer middleware for our framework.

I hope you like it!

See you soon!

Top comments (3)

Collapse
 
erasmusantwi profile image
Erasmus Antwi

I love this! Thank you very much sir. is this the last part or more on the way?

Collapse
 
wesleymreng7 profile image
Wesley Miranda

I am creating more parts

Collapse
 
erasmusantwi profile image
Erasmus Antwi

incredible! please keep them coming. would be great if you could add functionality like express-async-errors