Express app.post() Method
What you’ll learn
- How to define POST routes using
app.post(path, handler). - How to read and validate incoming body data with
req.body. - How to return proper creation responses for APIs and forms.
- How to avoid common POST route pitfalls.
Overview
app.post() handles HTTP POST requests and is typically used for create actions and submitted data processing.
Create operations
Best suited for adding resources such as users, posts, or orders.
Body-driven input
Reads incoming payload data via req.body after body parser setup.
Validation first
Validate payloads before database writes or side effects.
Syntax
javascript
app.post(path, callback)
app.post(path, middleware1, middleware2, ..., callback)- path: route path pattern for POST requests.
- callback/middleware: handler chain executed on route match.
- Use
express.json()(or relevant parser) to populatereq.body.
1
Basic POST route
javascript
const express = require('express');
const app = express();
app.use(express.json());
app.post('/messages', function (req, res) {
res.status(201).json({ created: true, data: req.body });
});2
Validation before create
javascript
app.post('/users', function (req, res) {
var name = (req.body && req.body.name) || '';
if (!name.trim()) {
return res.status(400).json({ error: 'Name is required' });
}
var user = { id: Date.now(), name: name.trim() };
res.status(201).json(user);
});📋 app.post() vs app.put()
| Method | Typical intent | Common status |
|---|---|---|
app.post() | Create new resource | 201 Created |
app.put() | Replace/update resource | 200 OK or 204 No Content |
🧪 Testing checklist
- Verify successful creation flow returns expected response payload.
- Test missing or invalid fields for proper validation errors.
- Confirm correct status codes (
201,400, etc.). - Check parser behavior for JSON and form data inputs.
Pitfalls to avoid
Missing parser
Empty req.body
Register body parsing middleware before POST routes.
No validation
Invalid data saved
Validate and sanitize incoming payloads before processing.
Wrong status code
Ambiguous API behavior
Use 201 for successful creation and meaningful errors otherwise.
❓ FAQ
It defines a route handler for HTTP POST requests on a specific path.
Use it when clients submit new data, such as creating a user, order, or comment.
Use body-parsing middleware like express.json() and access values in req.body.
Yes. You can chain validation, authentication, and business logic middleware before the final handler.
Usually yes. Return useful response details and an appropriate status code like 201 for creation.
Summary
- Core use:
app.post()handles create-style endpoints. - Inputs: use parsed request body data with strong validation.
- Practice: send clear status codes and consistent response payloads.
Did you know?
app.post(path, handler) is commonly used to create resources and process submitted form or API data.
4 people found this page helpful
