- Extracting data from either URI or request body
- req.params
- req.query
- req.body
- App.params
- Error logging middleware
router.get("/:urlTitle", (req, res, next) => {
req.params.urlTitle
});
Also is used when doing a form with method GET
// /search?tag=foo
router.get("/search", (req, res, next) => {
req.query.tag
});
Used when doing a form with method POST
and body-parser middleware
router.post("/", (req, res, next) => {
name: req.body.name,
email: req.body.email
});
This allows you to process information in the parameters of the passed in URI.
For more information look at this blog post.
// App.param - /:id
router.param("id", (req, res, next, id) => {
Article.findById(id)
.then((article) => {
req._articleById = article; // Store the found article on the request object, that can be used in subsequent routes
next(); // This is crucial to letting the program continue and not hang
})
.catch();
});
The basic structure of a app wide error catcher is:
// Error handling
app.use((err, req, res, next) => {
res.status(err.status || 500).send(err.message || 'Internal server error');
});
Here is a helper function to create new Error instances:
function createError(status, message) {
const err = new Error(message);
err.status = status;
return err;
}
Use the createError
function as follows in your routes:
Book.findById(bookId, queryObj) // Find the book by ID
.then((foundBook) => {
if (foundBook) {
req._book = foundBook; // Set the found book to the request variable
next();
} else {
next(createError(404, 'book not found'));
}
})
.catch(next);