Step 6
Handlers for URLs with parameters
Let's add some parameters in our URLs. We can add variables in our URLs and parse them in our router.
src/routes/books.js
...
router.get('/:id', async (req, res) => {
const { id } = req.params;
const book = await Book.findById(id);
if (!book) return res.status(404).send(`Book with ID: ${id} does not exist!`);
res.send(book);
});
...
The colon notation in the URL means that this is a variable called "id", which will show up in the params field of our HTTP request. Using that id, we return the book that corresponds to that id. If there is no book associated with that id, we return a 404 (Not Found) HTTP Error. You can test this route by making an HTTP GET request to "localhost:5000/api/books/someID"
Let's do the same thing for deleting a book.
src/routes/books.js
...
router.delete('/:id', async (req, res) => {
const { id } = req.params;
const book = await Book.findById(id);
if (!book) return res.status(404).send(`Book with ID: ${id} does not exist!`);
const removedBook = await book.destroy();
res.send(removedBook);
});
...
The only lines we changed are lines 2 and 7. We are processing a DELETE request instead of a GET request and we delete the book from the database and return it to the user.
Finally, let's do the same thing for updating a book
...
router.put('/:id', async (req, res) => {
const { id } = req.params;
const { title, author } = req.body;
const book = await Book.findById(id);
if (!book) return res.status(400).send(`Book with ID: ${id} does not exist!`);
if (title) book.title = title;
if (author) book.author = author;
await book.save();
res.send(book);
});
...
Here, we only update the title and author fields if the user has provided them. An HTTP PUT request is generally used for updating an existing resource and a POST request is generally used for creating a new resource.
Last updated
Was this helpful?