Working with JSON and Request Bodies

Site Admin · 11 Sep 2026 · 7 views

Working with JSON and Request Bodies

Most modern clients talk to APIs in JSON. Express parses incoming JSON for you when you mount the json middleware, and res.json writes JSON back out.

Parsing the body

Express keeps the raw request body empty until a parser runs:

app.use(express.json());

app.post('/register', (req, res) => {
  const { email, password } = req.body;
  console.log(email, password);
  res.json({ ok: true });
});

The middleware reads the stream, parses the JSON, and attaches the result to req.body as a plain object.

Sending JSON back

res.json serializes an object with proper headers and formatting:

res.json({ message: 'Welcome', user });

Handing objects straight to res.json is safer than hand-building strings.

Nested and larger payloads

JSON supports nesting, so req.body can hold deep structures, and responses reflect the same shape:

res.json({
  user: { name: 'Ada' },
  tags: ['js', 'api'],
});

Handling bad JSON

Malformed JSON makes the parser throw, and the error middleware returns a helpful message. Form submissions use express.urlencoded instead, which parses key-value pairs into req.body the same way.

Key Points

  • express.json parses incoming JSON bodies.
  • req.body holds the parsed JavaScript object.
  • res.json serializes responses as JSON.
  • Malformed JSON needs error-handling middleware.
  • urlencoded handles classic HTML form data.
Share this post:

Comments (0)

Please login or register to comment.