Custom middleware

There will undoubtedly come a time when you want to write your own custom middleware in addition to the existing middleware provided by Connect or any other third party. Before you write your own custom anything in Node, make it a habit to search through https://www.npmjs.org/ first, as there's a fairly big chance someone else has already done the work.

Writing your own custom middleware is pretty simple. You simply need to write a function that accepts four parameters: err, req, res, and next. The first parameter is an error object, and if there were any stack errors prior to your middleware running, that error will be passed to your middleware so you can handle accordingly. You are already familiar with the req and res parameters having written your routes. The fourth parameter is actually a reference to a callback. This next parameter is how the middleware stack is able to behave like a stack—each executing and ensuring that the next middleware in the pipeline is returned and called via next. Here is a super basic example of a custom middleware:

app.use(function(err, req, res, next) {
    // do whatever you want here, alter req, alter res, throw err, etc.
    return next();
});

The only important thing to keep in mind when writing your own custom middleware is that you have the correct parameters and that you return next(). The rest is completely up to you!

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

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