Why do you need the middleware bodyParser?

Posted by gibbo1715 on Mon, 03 Jan 2022 07:25:47 +0100

preface

I haven't written articles on JS development for many days, mainly because there are too many recent things. I don't know what to write today. Then I noticed that when we write http services, we usually directly use a middleware body parser to get the parameters passed in our post request.

Front end code

Let's take a look at our test code first,

The following is our page code today. I'll write it directly in html. On this page, we introduce a cdn link of axios, and then add a click button. After clicking the button, we will send a post request to the back end. In the request header, we add a JSON data to the server end.

/* index.html */

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <style>
    body {
      width: 100vw;
      height: 100vh;
      background-color: #fff;
    }
  </style>
</head>
<body>
  <button onclick="handlePost()">send data</button>

  <script>
    function handlePost() {
      axios.post('/data', {
        name: 'TT',
        age: '25'
      }).then((data) => {
        console.log(data)
      }).catch((error) =>{
        console.error(error)
      })
    }
  </script>
</body>
</html>

Back end code

Let's take another look at the back-end code;

On the server side, I will directly build a simple service with the express module, and then add a post request route here,

You can see here that the body parser middleware is not added,

First, print whether the body attribute exists in the request object, then print the body attribute value (if it exists), and finally don't forget to give a response to the request.

/* app.js */

const express = require('express');
const path = require('path')
const app = express();
app.use(express.static(path.join(__dirname)));

app.post('/data', (req, res) => {
  console.log(Object.keys(req).includes('body'), req.body)
  res.send('success')
})

app.listen(3000, '127.0.0.1', () => {
  console.log(`Server running at http://127.0.0.1:3000`)
});

Look directly at the printed results

From the print results, there is no body attribute in our request object at this time. How can we get the transmitted data?

We all know that we generally initiate post type network requests, and the request data will be placed in the body, but we did not get our body from the request object in the above printing, because here, our body data is transmitted to our server in the form of data flow, but our transmission data is placed in the body, Then we must get our data by receiving the data stream. Let's take a look at the code after receiving the data stream.

/* app.js */

const express = require('express');
const path = require('path')
const app = express();
app.use(express.static(path.join(__dirname)));

app.post('/data', (req, res) => {
  console.log(Object.keys(req).includes('body'), req.body)

  const chunkData = [];
  let size = 0;
  req.on('data', data => {
    console.log('data: ', data instanceof Buffer)
    chunkData.push(data);
    size += data.length;
  })

  req.on('end', () => {
    const data = Buffer.concat(chunkData, size)
    console.log('end: ', size, data.toString());
    res.send('success')
  })
})

app.listen(3000, '127.0.0.1', () => {
  console.log(`Server running at http://127.0.0.1:3000`)
});

Here, in the post request routing callback on the server, I listen to the data and end events of the request object, receive the body data transmitted through the stream in the data event, then merge the data stream in the end event after receiving the data, and then print it in the form of string. Let's take a look at the print results.

You can see that the data type we get in the data event is indeed stream data, and after receiving all the data streams, we print the data through the string type in the end event. At this time, we can see that the JSON data we pass to the service through the page is successfully printed.

It shows that we can receive the data transmitted by the front-end post request in the form of flow, but it must be troublesome to process it every time. Therefore, we generally process the data flow of our post request directly through the body parser middleware.

So here, you should also know what our body parser middleware does. Of course, here I just show you the basic content, but in the middleware, there are still many situations to deal with,

Finally, let's install the middleware body parser and see the effect,

/* app.js */
const express = require('express');
const path = require('path')
const app = express();
const bodyParser = require('body-parser');
app.use(express.static(path.join(__dirname)));
app.use(bodyParser.json());

app.post('/data', (req, res) => {
  console.log(Object.keys(req).includes('body'), req.body)
  res.send('success')
})

app.listen(3000, '127.0.0.1', () => {
  console.log(`Server running at http://127.0.0.1:3000`)
});

You can see that after using the body parser middleware, there is an additional body attribute in our request object. When printed, you can see that it is the data parameters passed by our front end.

If you are interested, you can also take a look at the source code of the middleware body parser. We won't post the source code here

summary

It's not 2022 right now. There's a lot of work in hand recently, so the article update may reduce the frequency. If the content is wrong, you are also welcome to leave a message. Thank you for your appreciation!

Topics: Javascript node.js