Selected topic
Request Handling
Prefer practical output? Use related tools below while reading.
When handling HTTP requests, it's often necessary to parse the request body to extract and process data sent by the client. In Express.js, this is achieved through a middleware called body-parser.
javascript
const express = require('express');
const bodyParser = require('body-parser');const app = express();
// Enable parsing of JSON bodies
app.use(bodyParser.json());
// Define a route to handle POST requests
app.post('/users', (req, res) => {
const { name, age } = req.body;
console.log(Received request with name: ${name}, age: ${age});
// Process the data...
res.send(User created successfully!);
});
// Listen on port 3000
const port = 3000;
app.listen(port, () => {
console.log(Server listening on port ${port}...);
});
body-parser as a middleware.app.use(bodyParser.json()) to enable parsing of JSON bodies in the request./users.req.body.body-parser) to parse and extract the data from the request.The parsed data is then stored in the req.body object, which can be accessed within route handlers. This allows you to easily access and process the client-provided data in a structured way.
body-parser.json() for JSON, body-parser.urlencoded({ extended: true }) for form data).