AlexKolonitsky / mifort-dev

GNU General Public License v3.0
5 stars 0 forks source link

Nick - ExpressJS: Middleware #32

Open NickBerilov opened 6 years ago

NickBerilov commented 6 years ago

You might've heard about ExpressJS: probably the most popular Node.js framework. You might've also heard the word middleware a whole lot. But what is middleware?

Your standard Express-application usually consists of a bunch of routes (also calles endpoints), as well as a number of handlers for each of these routes, which are executed consecutively. These handlers are called middleware. Now let's go into some detail.

Middleware functions (except for error-handling middleware, we'll cover them later) have access to the request object (req), response object (res), as well as the next middleware function. Middleware functions can do several things:

Here's an example: let's have a look at a simple "Hello world" app.

var express = require('express')
var app = express()

app.get('/', function (req, res) {
  res.send('Hello World!')
})

app.listen(3000)

The '/' route has a single middleware function that ends the request-response cycle by responding with "Hello world!". And here's a simple logger function:

const logger = function (req, res, next) {
  console.log(req.path);
  next()
}

Now, there are multiple ways to add this function as a middleware function. You can:

  1. Add it to a single route (in which case the function is executed for this route only):
    app.get('/', logger, function (req, res) {
      res.send('Hello World!')
    })
  2. Add it to a Router (function is executed for each route within the rootRouter):
    const rootRouter = express.Router()
    //...
    const router = express.Router()
    router.use('/root', logger, rootRouter)
  3. Add it to the whole app (function is executed for every route, that is defined after app.use):
    app.use(logger);

    There are several types of middleware:

  4. Binding a function to an instance of the app object by using the app.use() or app.METHOD() makes it application-level middleware. It's important to note here that the order in which you add application-level middleware to your app matters: as with all types of middleware, application-level middleware will be executed (or checked for, in case of routes) in order it was defined.
  5. Router-level middleware is similar to application-level, except it is bound to an instance of express.Router()
  6. Error-handling middleware. Passing anything to the next() function (except the string 'route') will skip any remaining non-error-handling middleware an pass control to the first error-handling middleware. Unlike other middleware function, error-handling middleware accept four arguments: err, req, res, next:
    function errorHandler (err, req, res, next) {
      if (res.headersSent) {
        return next(err)
      }
      res.status(500)
      res.render('error', { error: err })
    }
  7. Starting with version 4.x, the only remaining built-in middleware is express.static, which is used to serve static content:
    express.static(root, [options])

    See the official documentation for more details

  8. Third-party middleware is used to extend the functionality of Express apps (e.g. cookie-parser, body-parser).

To sum up, middleware functions make Express apps customizable and easy to build by allowing to add stuff like error-handlers, validation, loggers and application logic to both single and multiple routes, as well as increase functionality by adding libraries as midleware functions.

Czech-nut commented 6 years ago

@NickBerilov Please rewrite the article image

NickBerilov commented 6 years ago

@Czech-nut The tool found a lot of matches between the article and the official Express documentation and other articles about Express, most of them being terminology (e.g. application-level middleware, end the request-response cycle) and common code. Considering that the main goal of the article is to concisely convey everything about middleware from said documentation I will be unable to rewrite it without either avoiding the essential terms and code examples (making the article pointless) or completely changing the topic