POST Routes and JSON Bodies
A POST route is a handler that accepts new data. The data arrives as a JSON body, so the route reads it from the request.
Reading JSON bodies
express.json is middleware that reads a JSON body.
app.use(express.json());A POST route
The body becomes the new note.
app.post('/api/notes', async (req, res) => {
const note = await Note.create(req.body);
res.json({ title: note.title, done: note.done });
});Creating a note
curl sends the new note as JSON.
curl -X POST http://localhost:3001/api/notes -H "Content-Type: application/json" -d '{"title":"Water plants","done":false}'Example
import express from 'express';
import mongoose from 'mongoose';
await mongoose.connect('mongodb://localhost:27017/notes');
const noteSchema = new mongoose.Schema({ title: String, done: Boolean });
const Note = mongoose.model('Note', noteSchema);
await Note.create({ title: 'Buy milk', done: false });
await Note.create({ title: 'Ship MERN', done: true });
await Note.create({ title: 'Read a book', done: false });
const app = express();
app.use(express.json());
app.post('/api/notes', async (req, res) => {
const note = await Note.create(req.body);
res.json({ title: note.title, done: note.done });
});
app.get('/api/notes', async (req, res) => {
const notes = await Note.find().sort({ title: 1 });
res.json(notes.map((n) => ({ title: n.title, done: n.done })));
});
const server = app.listen(0);
const port = server.address().port;
const base = `http://localhost:${port}`;
const created = await fetch(`${base}/api/notes`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'Water plants', done: false }),
});
console.log(await created.text());
const list = await fetch(`${base}/api/notes`);
console.log(await list.text());
server.close();
await mongoose.disconnect();Key points
- A POST route creates something new on the server.
- The new data arrives in the request body.
- express.json is middleware that reads a JSON body.
- It puts the parsed object on req.body, ready to save.
- The route sends the saved note back as JSON.
In this example, the script connects to the notes database and saves the three notes. It builds an Express app and adds express.json, so a JSON body reaches req.body. The POST route saves the body as a new note and sends it back. The script sends a POST request with a new note, then asks for the full list. The first printed line is the new note, and the second line is the list with four notes.
Note
Without express.json, req.body has no value.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does express.json do?