Build a POST API endpoint
Create an endpoint that accepts submitted form or JSON data and returns a response.
Express.js · Function
app.post() routes HTTP POST requests matching a specified path to one or more callback functions. The callbacks can act as middleware and may pass control to later handlers or skip the remaining callbacks for the current route.
app.post() registers one or more callbacks for HTTP POST requests whose URL matches the supplied path. Express invokes the callbacks in order, allowing middleware to process the request before a handler sends the response or passes control onward.
app.post(path, [callback ...], callback)| Name | Type | Description |
|---|---|---|
path | String | RegExp | Array | A string, path pattern, regular expression, or array of supported path specifications to match. |
callback… | Function | One middleware function, multiple callbacks, an array of callbacks, or a combination of these. |
import express from 'express';
const app = express();
app.use(express.json());
app.post('/users', (req, res) => {
res.status(201).json({ user: req.body });
});
app.listen(3000);Parses JSON request bodies, then handles POST requests to /users and returns the submitted data.
Create an endpoint that accepts submitted form or JSON data and returns a response.
Run authentication, validation, or request preprocessing before the final handler.
Match several URL forms with one callback chain using supported path specifications.
app.post() defines a route for HTTP POST requests at a specified path. Its callbacks receive the request and response objects and can process input or send a response.
Follow-up: How can a POST route use multiple handlers? Pass multiple callbacks; they run as middleware in order, and a handler can pass control onward with next().
The path may be a string, path pattern, regular expression, or an array combining those forms. Express matches the incoming request URL against that path before invoking the callbacks.
Follow-up: Why might an array be useful? It lets one route declaration match multiple path specifications without duplicating the callback list.
The callback argument may be one middleware function, several comma-separated functions, an array of functions, or a combination. These callbacks can invoke next('route') to skip the remaining callbacks for the current route.
Follow-up: What happens after next('route')? Express bypasses the rest of that route's callbacks and proceeds to a subsequent matching route, if one exists.
app.get()app.put()app.delete()app.query()router.post()express.Router()