The Request Journey
The request journey is the path one request takes through the stack. It starts in React and ends in the database, then returns.
React sends the request
fetch(API_URL + '/notes')Express matches the route
app.get('/notes', async (req, res) => {
const notes = await Note.find().sort({ title: 1 });
res.json(notes.map((n) => ({ title: n.title, done: n.done })));
});Mongoose reads the notes
await Note.find().sort({ title: 1 });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('JourneyNote', 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.get('/notes', async (req, res) => {
console.log('Step 2: Express matches the GET /notes route');
console.log('Step 3: Mongoose reads the notes from MongoDB');
const notes = await Note.find().sort({ title: 1 });
res.json(notes.map((n) => ({ title: n.title, done: n.done })));
});
const server = app.listen(0);
await new Promise((resolve) => server.once('listening', resolve));
const port = server.address().port;
console.log('Step 1: React sends a fetch request to /notes');
const response = await fetch('http://localhost:' + port + '/notes');
const notes = await response.json();
console.log('Step 4: The response reaches React:');
console.log(JSON.stringify(notes));
await new Promise((resolve) => server.close(resolve));
await mongoose.disconnect();Key points
- The journey has four stops: React, Express, Mongoose, and MongoDB.
- React sends a fetch request to the API address.
- Express matches the route and asks Mongoose for the notes.
- Mongoose reads the documents from MongoDB and hands them back.
- The response travels back along the same path to React.
In this example, the script seeds the three notes. It starts the API on a free port chosen by the system. Step 1 prints before the fetch. Steps 2 and 3 print inside the route while the request is handled. Step 4 prints the response that reaches React. The printed list is the same data at every stop, sorted by title.
Note
The journey is the same for every request, whatever the route is.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What happens at the Express stop of the journey?