Handling HTTP POST Requests
A POST request sends data to the server to create something new: a user account, an order, a comment. In Express you handle it with app.post() and read the submitted data from req.body. Unlike GET requests, which carry their information in the URL, POST requests carry it in the request body, usually as JSON when the client is a JavaScript app.
Parsing the request body first
Express does not read the body by default, so req.body is undefined until you add a body-parsing middleware. For JSON, use the built-in express.json(). For classic HTML forms, which send application/x-www-form-urlencoded data, add express.urlencoded({ extended: true }). Register these before your routes.
const express = require('express');
const app = express();
app.use(express.json({ limit: '100kb' }));
const books = [];
let nextId = 1;
app.post('/api/books', (req, res) => {
const { title, author, pages } = req.body ?? {};
if (typeof title !== 'string' || title.trim() === '') {
return res.status(400).json({ error: 'title is required' });
}
if (pages !== undefined && (!Number.isInteger(pages) || pages <= 0)) {
return res.status(400).json({ error: 'pages must be a positive integer' });
}
const book = {
id: nextId++,
title: title.trim(),
author: author?.trim() || 'Unknown',
pages: pages ?? null
};
books.push(book);
res.status(201).location(`/api/books/${book.id}`).json(book);
});
app.listen(3000, () => console.log('API on http://localhost:3000'));
Validating what arrives
Never trust the body. A client can send missing fields, wrong types, extra properties or huge payloads. Check every field you use, reject bad input with 400 Bad Request and a helpful message, and copy only the fields you expect into the new record. Building the object field by field, as above, prevents a client from sneaking in properties such as isAdmin: true. Larger projects often use a schema validation library to describe these rules in one place.
The limit option on express.json() rejects oversized bodies before your code even runs.
In a real application the new record goes into a database rather than an in-memory array, which is lost whenever the server restarts. The database call is asynchronous, so the handler becomes an async function. Wrap the insert in try/catch and pass unexpected errors to next(err), while turning known problems, such as a unique-key violation for a duplicate email, into clear client errors. Let the database generate the ID rather than trusting one sent by the client.
Answering with the right status
When a POST creates a resource, reply with 201 Created and include the new record, with its server-generated ID, in the response. Setting the Location header to the new resource's URL is a helpful REST convention. Use 400 for invalid input, 409 Conflict for duplicates such as an email already registered, and let unexpected failures fall through to an error handler that returns 500.
Why req.body is empty
If req.body is undefined or {}, check three things. First, is express.json() registered before the route? Second, does the client send the header Content-Type: application/json? Without it, the JSON parser skips the body. Third, did the client actually stringify the data? A fetch call should look like this:
await fetch('/api/books', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'Wings of Fire', pages: 180 })
});
Malformed JSON makes express.json() respond with a 400 error on its own, so your route never runs.
To test the route without writing a frontend, send a request from an API client such as Postman or from the terminal with curl, setting the method to POST, the content type to JSON and a raw JSON body.
Main points
- Register a body parser, then read
req.body. - Validate every field and copy only what you expect.
- Return
201with the created record.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.