Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the parameter "next" used for in Express?

Suppose you have a simple block of code like this:

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

This function has two parameters, req and res, which represent the request and response objects respectively.

On the other hand, there are other functions with a third parameter called next. For example, lets have a look at the following code:

app.get('/users/:id?', function(req, res, next){ // Why do we need next?     var id = req.params.id;     if (id) {         // do something     } else {         next(); // What is this doing?     } }); 

I can't understand what the point of next() is or why its being used. In that example, if id doesn't exist, what is next actually doing?

like image 636
Menztrual Avatar asked May 22 '12 04:05

Menztrual


People also ask

What does next () do in Express?

The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware. Middleware functions can perform the following tasks: Execute any code. Make changes to the request and the response objects.

What does next () do in node?

In this is article we will see when to use next() and return next() in NodeJS. Features: next() : It will run or execute the code after all the middleware function is finished. return next() : By using return next it will jump out the callback immediately and the code below return next() will be unreachable.

What is next used for?

Background. Next. js is a React framework that enables several extra features, including server-side rendering and generating static websites. React is a JavaScript library that is traditionally used to build web applications rendered in the client's browser with JavaScript.

What is next () in js?

The next() method returns an object with two properties done and value . You can also provide a parameter to the next method to send a value to the generator.


2 Answers

It passes control to the next matching route. In the example you give, for instance, you might look up the user in the database if an id was given, and assign it to req.user.

Below, you could have a route like:

app.get('/users', function(req, res) {   // check for and maybe do something with req.user }); 

Since /users/123 will match the route in your example first, that will first check and find user 123; then /users can do something with the result of that.

Route middleware is a more flexible and powerful tool, though, in my opinion, since it doesn't rely on a particular URI scheme or route ordering. I'd be inclined to model the example shown like this, assuming a Users model with an async findOne():

function loadUser(req, res, next) {   if (req.params.userId) {     Users.findOne({ id: req.params.userId }, function(err, user) {       if (err) {         next(new Error("Couldn't find user: " + err));         return;       }        req.user = user;       next();     });   } else {     next();   } }  // ...  app.get('/user/:userId', loadUser, function(req, res) {   // do something with req.user });  app.get('/users/:userId?', loadUser, function(req, res) {   // if req.user was set, it's because userId was specified (and we found the user). });  // Pretend there's a "loadItem()" which operates similarly, but with itemId. app.get('/item/:itemId/addTo/:userId', loadItem, loadUser, function(req, res) {   req.user.items.append(req.item.name); }); 

Being able to control flow like this is pretty handy. You might want to have certain pages only be available to users with an admin flag:

/**  * Only allows the page to be accessed if the user is an admin.  * Requires use of `loadUser` middleware.  */ function requireAdmin(req, res, next) {   if (!req.user || !req.user.admin) {     next(new Error("Permission denied."));     return;   }    next(); }  app.get('/top/secret', loadUser, requireAdmin, function(req, res) {   res.send('blahblahblah'); }); 

Hope this gave you some inspiration!

like image 125
Asherah Avatar answered Sep 28 '22 04:09

Asherah


I also had problem understanding next() , but this helped

var app = require("express")();  app.get("/", function(httpRequest, httpResponse, next){     httpResponse.write("Hello");     next(); //remove this and see what happens  });  app.get("/", function(httpRequest, httpResponse, next){     httpResponse.write(" World !!!");     httpResponse.end(); });  app.listen(8080); 
like image 45
rajesk Avatar answered Sep 28 '22 02:09

rajesk