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
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}`) })
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 }
You will receive the following response:
name: Wesley Miranda, age: 28
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 (6)
Please make the part 7 !!!
I stopped due to new priorities, but I am going to create new parts ASAP
I love this! Thank you very much sir. is this the last part or more on the way?
I am creating more parts
incredible! please keep them coming. would be great if you could add functionality like express-async-errors
Can someone help me, i cant use '/' endpoint, like app.get('/'. func)