GET Routes for Notes
A GET route is a handler that answers a read request. It runs when a browser or an app asks for data at its path.
A GET route
The path names the resource.
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 })));
});Sending only two fields
Only the title and done fields travel.
res.json(notes.map((n) => ({ title: n.title, done: n.done })));Asking for the list
curl asks the server for the notes.
curl http://localhost:3001/api/notesExample
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.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 res = await fetch(`${base}/api/notes`);
console.log(await res.text());
server.close();
await mongoose.disconnect();Key points
- A GET route never changes stored data.
- The path names the resource, such as /api/notes.
- The handler reads the notes and sends them back as JSON.
- res.json turns a value into a JSON response.
- The same route answers every time the path is asked for.
In this example, the script connects to the notes database and saves the three notes. It builds an Express app with one GET route for /api/notes. The route reads the notes, sorts them by title, and sends back only the title and done fields. The script starts the server on a free port and asks for the list. The printed line is the JSON body of the answer.
Note
The list is sorted by title, so the order stays steady.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does a GET route do?