app.post()
| Since: | Express 4(2014) |
|---|
The app.post() method in Express defines a route that handles POST requests to the specified path. Pass a path as the first argument and one or more handler functions as subsequent arguments to register the processing to be invoked when a POST request arrives at that path. It is mainly used in situations where the client sends data to the server, such as form submissions and API data posts.
Syntax
// Basic syntax for a POST route app.post(path, handler); // Specifying multiple handlers app.post(path, middleware, handler);
Parameters
| Parameter | Type | Description |
|---|---|---|
| path | String / Regular expression | Specifies the path to apply the route to. |
| handler | Function | Specifies the callback function that processes the request. Receives req, res, and next. |
Handler Function Arguments
| Argument | Description |
|---|---|
| req | The request object. Provides access to the request body, headers, URL parameters, and more. |
| res | The response object. Provides methods for sending a response to the client. |
| next | A function that passes control to the next middleware or route handler. |
Middleware Required to Access req.body
Without registering middleware, req.body will be undefined for POST request bodies. Register one of the following via app.use() in advance, depending on the format of the submitted data.
| Middleware | Target Content-Type | Description |
|---|---|---|
| express.json() | application/json | Parses a JSON-formatted request body and stores it in req.body. |
| express.urlencoded({ extended: true }) | application/x-www-form-urlencoded | Parses an HTML form submission body and stores it in req.body. |
Sample Code
The following examples cover basic POST route definitions, retrieving JSON bodies and form data, and using multiple handlers with validation in between.
var express = require('express');
var app = express();
// --- Register middleware ---
// Register middleware to parse JSON request bodies
app.use(express.json());
// Register middleware to parse HTML form submission request bodies
app.use(express.urlencoded({ extended: true }));
// --- Basic POST route ---
// Register a new user on POST requests to /users
app.post('/users', function(req, res) {
// Access the request body via req.body (requires express.json())
var name = req.body.name;
var email = req.body.email;
console.log('Received data:', name, email);
// Respond with status code 201 (Created)
res.status(201).json({ message: 'Registered successfully', name: name, email: email });
});
// --- Receiving submissions from an HTML form ---
// Route corresponding to a form with action="/login" method="POST"
app.post('/login', function(req, res) {
// With express.urlencoded() registered, form data is available via req.body
var username = req.body.username;
var password = req.body.password;
if (username === 'admin' && password === 'secret') {
// Redirect to the dashboard on successful authentication
res.redirect('/dashboard');
} else {
// Return 401 on failed authentication
res.status(401).json({ error: 'Incorrect username or password' });
}
});
// --- Combining URL parameters and request body ---
// Add a comment to /posts/:id/comments (e.g., /posts/42/comments)
app.post('/posts/:id/comments', function(req, res) {
// Retrieve the URL parameter via req.params.id
var postId = req.params.id;
// Retrieve the comment body via req.body.text
var text = req.body.text;
res.status(201).json({ postId: postId, comment: text });
});
// --- Multiple handlers with validation ---
// Define a middleware function to validate input values
function validateUser(req, res, next) {
var name = req.body.name;
var email = req.body.email;
// Check that both name and email are present
if (!name || !email) {
// Return 400 and stop processing if either is missing
return res.status(400).json({ error: 'name and email are required' });
}
// If validation passes, call next() to pass control to the next handler
next();
}
// Only requests that pass validateUser reach the registration handler
app.post('/members', validateUser, function(req, res) {
res.status(201).json({ message: 'Member registered successfully', data: req.body });
});
// --- Start the server ---
app.listen(3000, function() {
console.log('Server started: http://localhost:3000');
});
Notes
app.post() is the most fundamental way to receive POST requests. To access req.body, you must register a body-parsing middleware (express.json() or express.urlencoded()) via app.use() beforehand. If you forget to register it, req.body will be undefined.
By using a middleware chain with multiple handlers, you can insert shared processing such as validation and authentication into each route. Calling next() passes control to the next handler; if it is not called, processing stops at that point.
As your application grows larger, you can use express.Router() to split routes across files, making your code easier to organize. See also app.get() for how to define GET routes.
If you find any errors or copyright issues, please contact us.