Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nick - ExpressJS: Middleware #32

Open
NickBerilov opened this issue Sep 26, 2017 · 2 comments
Open

Nick - ExpressJS: Middleware #32

NickBerilov opened this issue Sep 26, 2017 · 2 comments
Assignees

Comments

@NickBerilov
Copy link
Collaborator

NickBerilov commented Sep 26, 2017

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:

  • Change the req and res objects
  • End the request-response cycle (e.g. by calling res.end() or res.send())
  • Call the next middleware function (if the current middleware function doesn't end the request-response cycle, it should call next(), or the request will be left hanging)
  • Execute code

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:

  1. 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.
  2. Router-level middleware is similar to application-level, except it is bound to an instance of express.Router()
  3. 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 })
    }
  4. 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
  5. 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
Copy link
Collaborator

@NickBerilov Please rewrite the article image

@NickBerilov
Copy link
Collaborator Author

@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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants