- Building Enterprise JavaScript Applications
- Daniel Li
- 344字
- 2021-07-23 16:31:25
Using body-parser middleware
That's just the start of our Express journey. The power of Express is in its abundance of middleware, which are functions that every request passes through. These middleware functions can opt to modify the request object before it arrives at the handler.
Therefore, instead of working with streams and buffers to obtain our payload data, we can make use of a very popular middleware package, body-parser. body-parser provides the ability to parse request bodies into JavaScript objects, which can then be consumed by our handlers. It does this in an efficient and optimized way, and also provides safeguards to ensure the payload is not too large. So, let's install it:
$ yarn add body-parser
Then, add the following lines to the top of src/index.js to instruct our application server to use the body-parser package to parse any request that has a JSON body:
import bodyParser from 'body-parser';
...
app.use(bodyParser.json({ limit: 1e6 }));
The bodyParser.json method returns with a middleware. Here, we are using the app.use() method to instruct our instance of the Express server to use the middleware generated by the bodyParser.json method. The middleware will parse the payload and assign it to the body property of the req object. We no longer need to work with streams and buffers; we can simply get the payload from req.body!
Inside our app.post('/users') call, remove any code that works with buffers and streams, and replace the payloadData variable with req.body. Lastly, replace the condition req.body.length === 0 inside our first if block with req.headers['content-length'] === '0'. Our handler should now look like this:
app.post('/users', (req, res) => {
if (req.headers['content-length'] === 0) {
res.status(400);
res.set('Content-Type', 'application/json');
res.json({
message: 'Payload should not be empty',
});
return;
}
if (req.headers['content-type'] !== 'application/json') {
res.status(415);
res.set('Content-Type', 'application/json');
res.json({
message: 'The "Content-Type" header must always be "application/json"',
});
return;
}
res.status(400);
res.set('Content-Type', 'application/json');
res.json({
message: 'Payload should be in JSON format',
});
});