How to Handle POST Request in Express API Correctly
POST request in an Express API, use app.post() with a route and a callback function. Make sure to include express.json() middleware to parse JSON request bodies before accessing req.body.Why This Happens
When you try to handle a POST request in Express without parsing the request body, req.body will be undefined. This happens because Express does not parse incoming JSON or URL-encoded data by default.
import express from 'express'; const app = express(); app.post('/submit', (req, res) => { console.log(req.body); // undefined res.send('Received POST request'); }); app.listen(3000, () => console.log('Server running on port 3000'));
The Fix
Add the express.json() middleware before your routes to parse JSON request bodies. This middleware reads the incoming JSON data and makes it available as req.body.
import express from 'express'; const app = express(); app.use(express.json()); // Middleware to parse JSON bodies app.post('/submit', (req, res) => { console.log(req.body); // Now contains the parsed JSON object res.send('Received POST request with data'); }); app.listen(3000, () => console.log('Server running on port 3000'));
Prevention
Always include body-parsing middleware like express.json() for JSON or express.urlencoded() for form data before defining routes that handle POST requests. Use linting tools and code reviews to ensure middleware is properly configured.
Test your API endpoints with tools like Postman or curl to verify that the server correctly receives and parses request bodies.
Related Errors
1. req.body is undefined: Usually caused by missing body-parser middleware.
2. SyntaxError: Unexpected token in JSON: Happens when the client sends invalid JSON; ensure the client sends properly formatted JSON.
3. 404 Not Found on POST route: Check that the route path and HTTP method match exactly.
Key Takeaways
express.json() middleware to parse JSON bodies before handling POST requests.req.body after parsing middleware is applied.