In web development, handling HTTP requests is a fundamental task. When dealing with POST or PUT requests, you often need to parse the request body to extract data sent by the client. Express.js provides middleware like body-parser to simplify this process.
body-parser is a popular middleware used in Express applications to parse incoming request bodies in a middleware before your handlers, available under the req.body property. It supports parsing JSON, URL-encoded, and raw text data.
Express itself does not come with built-in body-parsing capabilities, but it can be easily extended using middleware. body-parser is one such middleware that makes it straightforward to parse different types of request bodies.
Here’s how body-parser works:
req.body.JSON is a common format for sending structured data in HTTP requests. To parse JSON request bodies, you can use the body-parser.json() middleware.
First, you need to install the body-parser package if it's not already installed:
Data received
URL-encoded data is commonly used in HTML forms. To parse URL-encoded request bodies, you can use the body-parser.urlencoded() middleware.
Add the following code to your Express application:
1// Use body-parser to parse URL-encoded bodies2app.use(bodyParser.urlencoded({ extended: true }));34app.post('/form', (req, res) => {5console.log(req.body); // Access the parsed form data6res.send('Form data received');7});
You can test this endpoint by submitting a form or using curl:
Text received
In the next section, we will explore how to handle query parameters in Express.js. Query parameters are appended to URLs and can be used to pass data to your server.
Stay tuned for more insights into handling different types of request data in Express.js!