Read POST form fields in Express
Parse URL-encoded forms or JSON before the route, validate req.body, and use separate middleware for multipart uploads.
Install express.urlencoded() before the route to parse an ordinary URL-encoded form, then read its fields from req.body. Use express.json() for JSON requests. These built-in parsers were introduced in Express 4.16.0.
Parse and validate the form
Install Express with npm install express, then save this as server.cjs:
const express = require('express');
const app = express();
app.use(express.urlencoded({ extended: false, limit: '16kb' }));
app.use(express.json({ limit: '16kb' }));
app.post('/submit-form', (req, res) => {
const { username, password } = req.body || {};
if (typeof username !== 'string' || !username.trim() ||
typeof password !== 'string' || !password) {
return res.status(400).send('Username and password are required');
}
// Validate and process the fields here; this is not authentication code.
return res.send('Form received');
});
app.listen(3000, '127.0.0.1', () => console.log('Listening on port 3000'));
For an HTML page served from the same origin:
<form action="/submit-form" method="post">
<input name="username" />
<input name="password" type="password" />
<button type="submit">Submit</button>
</form>
The name attributes determine the submitted keys. This example checks basic shape only; a real login also needs the application's authentication, transport security, and request-forgery protections. Do not print passwords or entire credential-bearing bodies while debugging.
Match the parser to the content
- URL-encoded forms use
application/x-www-form-urlencodedandexpress.urlencoded(). - JSON uses
application/jsonandexpress.json(). - Multipart forms, including common file uploads, need middleware such as Multer or Busboy with appropriate limits.
The parser checks the request's content type. If none matches, req.body may be undefined; its default behavior differs across Express versions. Registering a parser after the route is too late.
extended: true permits richer nested structures, such as user[name]=Sam. extended: false suits simple fields but does not mean every value is necessarily a scalar: repeated keys can produce arrays. Validate the expected shape either way. Parser internals have changed over time, so choose based on documented behavior rather than assuming a particular underlying library.
FAQ
What if an older application uses body-parser? Earlier Express versions need that separate package for these parsers. Upgrade unsupported dependencies where possible; the built-in JSON and URL-encoded middleware is available from 4.16.0, not only 4.16.1.
Are GET parameters in req.body? URL query parameters are in req.query; route parameters such as /users/:id are in req.params. The request method does not relocate those values into the body.
Why does fetch JSON arrive empty? Send a JSON string, set the matching content type, and ensure express.json() runs before the route. A JSON parser does not parse arbitrary text just because it resembles JSON.
Why is one field undefined? Check the submitted key and nesting, parser order, and content type. Inspect sanitized test data rather than logging a live request's secrets. Oversized or malformed bodies may be rejected by middleware before the route runs.
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan