How to Get Request Body in Express: Simple Guide
In Express, you get the request body by using built-in middleware like
express.json() or express.urlencoded(). These middlewares parse incoming request data and make it available on req.body inside your route handlers.Syntax
To access the request body in Express, you first add middleware to parse the body data. Then, inside your route handler, you use req.body to get the parsed data.
express.json(): Parses JSON data sent in the request body.express.urlencoded({ extended: true }): Parses URL-encoded form data.req.body: Object containing the parsed data.
javascript
import express from 'express'; const app = express(); // Middleware to parse JSON body app.use(express.json()); // Middleware to parse URL-encoded body app.use(express.urlencoded({ extended: true })); app.post('/example', (req, res) => { const data = req.body; // Access parsed request body here res.send(data); });
Example
This example shows a simple Express server that accepts JSON data in a POST request and sends it back in the response. It demonstrates how express.json() middleware parses the body and how req.body contains the data.
javascript
import express from 'express'; const app = express(); const port = 3000; // Parse JSON bodies app.use(express.json()); app.post('/data', (req, res) => { // req.body contains the parsed JSON data res.json({ received: req.body }); }); app.listen(port, () => { console.log(`Server running on http://localhost:${port}`); });
Output
Server running on http://localhost:3000
// When you send a POST request with JSON body {"name":"Alice"} to /data
// The response will be {"received":{"name":"Alice"}}
Common Pitfalls
Many beginners forget to add the body-parsing middleware before their routes, so req.body is undefined. Also, using the wrong middleware for the data type (e.g., missing express.json() for JSON) causes parsing to fail.
Another mistake is placing middleware after route definitions, which means routes won't see parsed bodies.
javascript
import express from 'express'; const app = express(); // WRONG: No middleware added app.post('/wrong', (req, res) => { res.send(req.body); // undefined }); // RIGHT: Add middleware before routes app.use(express.json()); app.post('/right', (req, res) => { res.send(req.body); // parsed data });
Quick Reference
- express.json(): Use for JSON request bodies.
- express.urlencoded({ extended: true }): Use for form data.
- req.body: Contains parsed data after middleware.
- Always add middleware before route handlers.
- Use appropriate middleware for the content type sent by the client.
Key Takeaways
Use express.json() middleware to parse JSON request bodies.
Use express.urlencoded({ extended: true }) middleware to parse URL-encoded form data.
Access the parsed data via req.body inside route handlers.
Always add body-parsing middleware before defining routes.
Without proper middleware, req.body will be undefined.