Skip to content

Latest commit

 

History

History
executable file
·
89 lines (74 loc) · 1.95 KB

express-notes.md

File metadata and controls

executable file
·
89 lines (74 loc) · 1.95 KB

Express Notes

Contents

  • Extracting data from either URI or request body
    • req.params
    • req.query
    • req.body
  • App.params
  • Error logging middleware

Extracting data from either URI or request body

req.params

router.get("/:urlTitle", (req, res, next) => {
    req.params.urlTitle
});

req.query

Also is used when doing a form with method GET

// /search?tag=foo
router.get("/search", (req, res, next) => {
    req.query.tag
});

req.body

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
});

Add.param

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();
});

Error logging middleware

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);