Home node.js Next () in Express

Next () in Express

Author

Date

Category

After another re-reading of the Express documentation. An understanding of the next () function never came to my mind. I ask you to explain to me. For what and in what cases it is necessary to use next () , what does this function return? Let’s take a simple example

app.get ('/ users /: id?', function (req, res, next) {
   var id = req.params.id;
   if (id) {
    // do something
  } else {
    next ();
  }
});

What does next ()

do in this case


Answer 1, authority 100%

The Express.js framework is built on the concept of middleware. The essence of this approach is that a request to each resource is processed not by one single action of the controller (I specifically omit possible preprocessors, etc.), but by a whole stack of functions.

At the same time, each of these functions can somehow change the request / response and transfer control to the next function. Also, some of the functions can generate a final response and give it to the user, thereby stopping the movement down the middleware stack.

The linking of middleware elements in Express is precisely done with the next function. This function can be used for two purposes:

  1. Transfer control to the next function on the stack (for this the next function is called without parameters ).
  2. Report an error to the framework and transfer control to specialized middleware (a error object is passed to the next function for this).

If the next function is not called , then this means that the movement down the function stack should be finished.

I will illustrate all of the above with an example. A typical node.js application using Express looks like this:

var app = require ('express') ();
// Here we will add time to each incoming request,
// when it arrived with millisecond precision. In real
// the application can have session initialization code here,
// authentication, authorization, or whatever.
app.use ('/', function (req, res, next) {
  req.initTimestamp = (new Date ()). getTime ();
  // Note that the "next" function is called WITHOUT PARAMETERS.
  // This allows control to be passed to the next handler.
  next ();
});
// This handler checks when the request was initialized and,
// if the number of milliseconds is even, then it fails.
// In real applications, this can be, for example, an error
// database connections.
app.use ('/', function (req, res, next) {
  if (req.initTimestamp% 2 === 0) {
    // Note that the "next" function is passed an ERROR OBJECT.
    // It will be used later.
    next (new Error ('Not today. Sorry.'));
  } else {
    // Just send the response back to the client. The call to "next" is NOT NECESSARY here,
    // all following handlers will be ignored.
    res.send ('The sun is shining. Have a nice day :)');
  }
});
// And here we handle all those errors that were passed
// as arguments to the "next" function. Note that the handler
// FOUR arguments. "err" is the same error object from
// previous handler.
app.use ('/', function (err, req, res, next) {
  // Just send an error message to the client.
  res.send (err.message);
  // And instead, we could easily transfer control
  // NEXT error handler, like this
  // next (err);
});

Answer 2

If the function does not send a response , then it must pass control further in turn.
That is, there must be either res or next , otherwise everything may freeze.


Answer 3

In this video, a clear explanation https://www.youtube.com/watch?v= ZX3QT0UWIFC
The bottom line is that Next () causes the following function if there are several in the query, and not one. For example, here is

app.get ('USERS', PAGINEDRESULTS (USERS), (REQ, RES) = & gt; {
  res.json (res.paginatedResults);
});

Inserted PaginatedResults (Users) , inside which should be next () otherwise the code is the following function (REQ, RES) = & gt; will not start

function paginatedresults (model) {
  ...
    Next ();
  ...
  }

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions