Node.js
CRUD routes
Write CRUD (Create, Read, Update, Delete) routes.
CRUD routes
The third lesson adds CRUD routes: Create, Read, Update, Delete. For now we do Read and Create. You use app.get("/books", ...) for Read and app.post("/books", ...) for Create.
The GET route returns all books with res.json(books). The POST route takes the new book from req.body, adds it with books.push() and returns it with res.status(201).json(req.body). 201 means “Created”. app.use(express.json()) automatically parses incoming JSON bodies; we added it to the starting code. Now the API can read and write data.
Adding data with POST
The POST route is used to add new data. It is defined with app.post("/books", (req, res) => { ... }). The data sent in the body lives in req.body.
First app.use(express.json()) must be called; otherwise req.body stays undefined. This middleware parses the JSON body automatically. Then you add the new book to the array with books.push(req.body). You give the “Created” status code with res.status(201); this is the REST standard for create operations. Finally you return the added book with .json(req.body). This lets the client confirm the data was added.
Exercise Define GET and POST /books routes
Define two routes. With app.get("/books", ...) return the books array as JSON with res.json. With app.post("/books", ...) add a book from req.body and respond with res.status(201).json(...). The self-request is ready.
Show example solution
app.get("/books", (req, res) => {
res.json(books);
});
app.post("/books", (req, res) => {
books.push(req.body);
res.status(201).json(req.body);
});
Test yourself
-
Match each piece to its role
- app.get
- Reads data
- app.post
- Writes data
- req.body
- Incoming body
- res.status(201)
- Created code
-
Where is the new book read from in the POST /books route?
app.post("/books", (req, res) => ...)
- req.params
- req.query
- req.body
- req.url
Show answer
req.body — Body data is parsed into req.body by express.json().
-
Complete the POST route
app.____("/books", (req, res) => { books.push(req.body); res.status(201).json(req.body); });
Show answer
app.post("/books", (req, res) => { books.push(req.body); res.status(201).json(req.body); });
Next lesson: Middleware