🎓 A1Learner
🔍
0 of 50 lessons completed

Reading Request Bodies

A request body is the data a send ask carries. Express reads it into req.body when the JSON reader is on.

Switch on the JSON reader

This line switches on the JSON reader.

app.use(express.json());

Send a note body

This command sends a note body to the server.

curl -X POST http://localhost:3000/echo -H "Content-Type: application/json" -d '{"text":"Buy milk"}'

Example

const express = require("express");

const app = express();

app.use(express.json());

app.post("/echo", (req, res) => {
  res.json({ text: req.body.text });
});

app.listen(3000, () => {
  console.log("Notes API running on http://localhost:3000");
});

Key points

  • A request body is the data a send ask carries.
  • The body often arrives as a JSON string.
  • Use express.json() to turn that string into an object.
  • Write app.use(express.json()) before the routes.
  • The reader fills req.body with the sent object.
  • Read req.body.text to get one field from it.

In this example, the app.use line switches on the JSON reader. The app.post line makes a POST route at /echo. The route function reads req.body.text from the sent body. It sends the text back as JSON. A POST ask with a note body gets the same text back.

Note

Without the reader line, req.body stays empty.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What fills req.body with the sent object?