After sending a response, how to complete processing the current request in Node / Express?

There are several posts on this subject, but not one of them answers the question directly, head. Let me clarify that I understand (or, as I think) the use of next (), next ('route'), return next (), return and their impact on the control flow. My entire middleware for the application consists of the app.use series, as in:

app.use(f1); app.use(f2); app.use(f3); app.use(f4); ... 

In each of these intermediaries, I have the opportunity to send a response and execute it without the need for further processing. My problem is that I cannot stop processing the transition to the next middleware.

I have a clumsy job. I just set the res.locals.completed flag after sending the response. In all environments, at the very beginning, I check this flag and skip processing in the middleware if the flag is set. In the very first middleware, this flag is not set.

Of course, there must be a better solution, what is it? I would think that Express will implicitly perform this check and pass middlewares through some specific method?

+7
middleware express
source share
1 answer

According to the express documentation at http://expressjs.com/guide/using-middleware.html

 If the current middleware does not end the request-response cycle, it must call next() to pass control to the next middleware, otherwise the request will be left hanging. 

therefore, if the middleware needs to complete the request-request earlier, just do not call next() , but make sure the middleware does complete the request-response by calling res.end , res.send , res.render or any method that implicitly calls res.end

 app.use(function (req, res, next) { if (/* stop here */) { res.end(); } else { next(); } }); 

Here is a server example showing that it is running

 var express = require('express'); var app = express(); var count = 0; app.use(function(req, res, next) { console.log('f1'); next(); }) app.use(function(req, res, next) { console.log('f2'); if (count > 1) { res.send('Bye'); } else { next(); } }) app.use(function(req, res, next) { console.log('f3'); count++; next(); }) app.get('/', function (req, res) { res.send('Hello World: ' + count); }); var server = app.listen(3000); 

you will see after 3 requests, the server shows "Bye" and f3 is not reached

+7
source share

All Articles