How it works...

Middleware and route configurations are very similar in Express. Route configurations are a specialized type of middleware based around Express' router object. Unlike Express route configurations, custom middleware can take any properties we want. Custom middleware acts as a closure that associates your custom parameters with Express's callback to handle the request:

middleware: function (params) {
return function (req, res, next) {
// this call back use both params & Express objects
}
}

By placing our middleware in Express's app.use method, we are wiring our middleware to a route in the same manner as our Express route configurations. We can also take this a step farther by nesting our middleware in an existing app.use configuration:

app.use('/', first, second, third, function(req, res, next) { /* fourth */ });

This scopes our middleware to the same path as the route configuration, and all middleware are processed in a sequential order. Express's next() callback will invoke the next middleware's callback as it is defined for a given route. This is an incredibly powerful way to deterministically transform and work with request data in our routes, but it is can also be easy to make mistakes with. Failing to call next() or calling next() too early can result in routes failing to return values or returning invalid ones. It's important to consider what asynchronous operations your middleware is handling and place your callback to proceed in the proper place.

Our session object provided by express-session has some predefined methods for persisting data on the session object. The save function is an asynchronous callback that will write the current state of the session object to a data store for us:

req.session.save(function (err) {
next();
});

By default, this store is a simple in-memory data store, but there are easy ways to make this store persistent.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.114.230