Nodejs and Connect "next" features

It seems that if I want to go to the "next" function in Nodejs (and possibly in Javascript in general?), I cannot pass parameters to the next function.

Here is what I mean:

app.get('/webpage', SomeFunction, NextFunction); function SomeFunction (req, res, next) { // Do things next(); } function NextFunction (req, res) { // Do other things } 

Now, if in SomeFunction I should have said next(req, res); , he does not work. It never comes to a method. Obviously, I cannot pass parameters directly ... but why my question? How does the following function know which parameters to use? Is it because they are called the same or automatically transmit the 1st and 2nd parameters? If NextFunction used blah, bleet instead of req, res , will it still work?

+4
source share
1 answer

This is a deliberate aspect of the Connect design (the node.js middleware responsible for this behavior). The next function that your middleware receives is not the next middleware on the stack; this is a function that Connect creates that requests the next middleware to process it (and also does some extra stuff to handle special cases, like when there is no โ€œnext middlewareโ€).

If your middleware should return a response, just do it. If this is not the case, this implies that some later middleware should return a response. If you need to pass data to this later part of the process, you must attach it to the corresponding part of the req request object.

For example, the associated bodyParser middleware is responsible for populating req.rawBody and req.body based on the contents of the request body. The basicAuth related middleware populates req.remoteUser based on HTTP authentication.

This is the pattern you should try to emulate: a middleware stack, each of which performs a basic incremental operation to process the request. If what you are trying to simulate does not fit into this paradigm, then you probably should just have one function to handle the request, from which you can call all your own application logic as you like.

+15
source

All Articles