Course:Node.js & Express/
Lesson

When a client sends data to your server, a sign-up form, a new blog post, a settings update, that data arrives in the body of the HTTPWhat is http?The protocol browsers and servers use to exchange web pages, API data, and other resources, defining how requests and responses are formatted. request. Unlike URL parameters and query strings, the body is raw bytes. Express cannot know in advance whether it is JSONWhat is json?A text format for exchanging data between systems. It uses key-value pairs and arrays, and every programming language can read and write it., form data, or a file upload, so it does not parse anything by default. You opt in by adding middlewareWhat is middleware?A function that runs between receiving a request and sending a response. It can check authentication, log data, or modify the request before your main code sees it..

Adding body parsing middlewareWhat is middleware?A function that runs between receiving a request and sending a response. It can check authentication, log data, or modify the request before your main code sees it.

Middleware in Express is a function that runs before your route handlerWhat is route handler?A Next.js file named route.js inside the app/ directory that handles HTTP requests directly - the App Router equivalent of API routes.. You add it with app.use(). For the two most common content types, Express ships with built-in parsers:

import express from 'express';
const app = express();

// Parses Content-Type: application/json
app.use(express.json());

// Parses Content-Type: application/x-www-form-urlencoded (HTML forms)
app.use(express.urlencoded({ extended: true }));

Put these lines near the top of your file, before any route definitions. They run on every request and attach the parsed result to req.body.

If you forget express.json() and try to read req.body.email, you will get TypeError: Cannot read properties of undefined. This is one of the most common beginner mistakes in Express. The fix is always the same: add the middleware.
02

Receiving JSONWhat is json?A text format for exchanging data between systems. It uses key-value pairs and arrays, and every programming language can read and write it. data

This is the most common pattern in modern APIs. The client sends JSON in the request body, and you read it from req.body:

// POST /users with body: { "name": "Alice", "email": "alice@example.com" }
app.post('/users', (req, res) => {
  const { name, email } = req.body;

  const newUser = {
    id: Date.now().toString(),
    name,
    email
  };

  res.status(201).json(newUser);
});

You can test this without a frontend using curl:

curl -X POST http://localhost:3000/users \
  -H "Content-Type: application/json" \
  -d '{"name":"Alice","email":"alice@example.com"}'

The -H "Content-Type: application/json" header is required. Without it, Express does not know the body is JSON, and the middlewareWhat is middleware?A function that runs between receiving a request and sending a response. It can check authentication, log data, or modify the request before your main code sees it. will skip it.

03

Receiving HTML form data

Traditional HTML forms send data in a format called application/x-www-form-urlencoded. It looks like a query stringWhat is query string?The part of a URL after the ? that carries optional key-value pairs (like ?page=2&limit=10) used for filtering, sorting, or pagination. but in the body. The express.urlencoded() middlewareWhat is middleware?A function that runs between receiving a request and sending a response. It can check authentication, log data, or modify the request before your main code sees it. decodes it into req.body:

// HTML: <form method="POST" action="/contact">
app.post('/contact', (req, res) => {
  const { name, email, message } = req.body;
  console.log('New message from', name, '-', message);
  res.send('Message received!');
});
The `extended
true option in express.urlencoded({ extended: true }) uses the qs library instead of the built-in querystring module. This allows nested objects like user[name]=Alice in form data. If your forms are simple, extended: false` is fine and slightly lighter.
04

Configuring body size limits

By default, Express accepts bodies up to 100 KB. For most APIs this is plenty, but you might need to adjust it:

// Increase limit globally
app.use(express.json({ limit: '10mb' }));

// Or set a larger limit for one specific route only
app.post('/import', express.json({ limit: '50mb' }), (req, res) => {
  // This route accepts large payloads; others stay at the default
  res.json({ imported: req.body.length });
});

Setting per-route limits is a good habit for endpoints that handle uploads or bulk imports, it protects the restWhat is rest?An architectural style for web APIs where URLs represent resources (nouns) and HTTP methods (GET, POST, PUT, DELETE) represent actions on those resources. of your APIWhat is api?A set of rules that lets one program talk to another, usually over the internet, by sending requests and getting responses. from being affected by a single heavy request.

05

Putting it together: a CRUDWhat is crud?Create, Read, Update, Delete - the four basic operations almost every application performs on data. APIWhat is api?A set of rules that lets one program talk to another, usually over the internet, by sending requests and getting responses. in memory

Here is a complete example that combines routing from the previous lesson with body parsing. It stores users in an array (no database needed yet):

import express from 'express';
const app = express();

app.use(express.json());

const users = [];

// CREATE
app.post('/users', (req, res) => {
  const { name, email } = req.body;
  const user = { id: Date.now().toString(), name, email };
  users.push(user);
  res.status(201).json(user);
});

// READ all
app.get('/users', (req, res) => {
  res.json(users);
});

// READ one
app.get('/users/:id', (req, res) => {
  const user = users.find(u => u.id === req.params.id);
  if (!user) return res.status(404).json({ error: 'User not found' });
  res.json(user);
});

// UPDATE (partial)
app.patch('/users/:id', (req, res) => {
  const user = users.find(u => u.id === req.params.id);
  if (!user) return res.status(404).json({ error: 'User not found' });
  Object.assign(user, req.body);
  res.json(user);
});

// DELETE
app.delete('/users/:id', (req, res) => {
  const index = users.findIndex(u => u.id === req.params.id);
  if (index === -1) return res.status(404).json({ error: 'User not found' });
  users.splice(index, 1);
  res.status(204).send();
});

app.listen(3000, () => console.log('Server on http://localhost:3000'));

This is a fully functional RESTWhat is rest?An architectural style for web APIs where URLs represent resources (nouns) and HTTP methods (GET, POST, PUT, DELETE) represent actions on those resources. API. It covers all four CRUD operations, returns appropriate status codes, and handles missing resources gracefully. The only thing missing is a real database, which is what the next moduleWhat is module?A self-contained file of code with its own scope that explicitly exports values for other files to import, preventing name collisions. covers.

OperationMethodPathStatus on success
CreatePOST/users201 Created
Read allGET/users200 OK
Read oneGET/users/:id200 OK
UpdatePATCH/users/:id200 OK
DeleteDELETE/users/:id204 No Content