简体   繁体   中英

How does node.js next() middleware function work without arguments?

Middleware functions have a signature function (req, res, next) , but in Express the next() call does not contain arguments. How is this so? See the following example from the sample documentation

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

var myLogger = function (req, res, next) {
  console.log('LOGGED')
  next()
}

app.use(myLogger)

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

app.listen(3000)

It certainly could be the case that a wrapping function is created that under-the-hood binds the arguments, allowing for a call with no additional parameters, but the documentation seems to indicate that the next parameter is called as-is, which does not make sense.

The docs describe the third argument, conventionally named next , as

Callback argument to the middleware function, called "next" by convention.

You can think of it similar to the conventional node.js callback-style argument provided to most async functions (without promises). When your middleware function is done doing its sync or async work, it should call next to indicate to the express router that it is done executing. This argument could be called done or callback , as we often see in other node.js libraries and examples, but is called next to provide a hint to the developer that the middleware chain will continue execution (other middleware may be called after this one).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM