Greg
Greg

Reputation: 370

expressjs where to call next() in middleware

What is the difference on calling next() outside the end() function or inside? Also does i need to call it into onError() ?

PS: I need the data in my next handler.

return function (req, res, next){

        req.setEncoding('utf8');
        req.rawBody = '';

        req.on('data', function (chunk) {
            req.rawBody += chunk;
        });

        req.on('aborted', onAborted);

        function onAborted() {
            logger.warn('Request has been aborted [IP= ' + req.ip + '].');
        }

        req.on('error', onError);

        function onError() {
            logger.warn('Unable to read request [IP= ' + req.ip + '].');
            // next() ?
        }

        req.on('end', onEnd);

        function onEnd() {
            next()
        }

        // next() ?
    };

Upvotes: 0

Views: 418

Answers (1)

Rodrigo Medeiros
Rodrigo Medeiros

Reputation: 7862

The difference is that inside onEnd it's going to be executed asynchronously only when the end event is emitted. Outside onEnd, in the last line, it will not wait for the end event and will be executed as soon as the code reaches that line.

When developing an express app, it's a good pratice to pass the error, when it happens, to the next() function, and handle that with a middleware (like errorHandler) in the main file.

Upvotes: 1

Related Questions