0
0
ExpressDebug / FixBeginner · 4 min read

How to Handle POST Request in Express API Correctly

To handle a 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.

javascript
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'));
Output
undefined
🔧

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.

javascript
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'));
Output
Received POST request with data
🛡️

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

Use express.json() middleware to parse JSON bodies before handling POST requests.
Access POST data safely via req.body after parsing middleware is applied.
Test your API endpoints with tools like Postman to confirm correct request handling.
Always define routes with the correct HTTP method and path to avoid 404 errors.
Validate client data to prevent JSON parsing errors on the server.