javascriptnode.jsexpress

How to use multiple request handling functions with Node.js Express?


I need to do a repetitive auth process in most routes in my app. I decided to give some structure to it and get that repetitive work in a middleware function.

If the auth process isn't valid, I should response and avoid second function to execute, terminating the request.

So, instead of:

app.route('/someRoute').all(function(request,response){});

I tried something like:

app.route('/someRoute').all(repetitiveWork,secondMiddlewareFunction);

In particular this is the dummy example I got:

app.route('/rutas').get(sum,test);


function sum (request,response,next) {

    if (5>1) {
        response.status(144).end('Fin');
        return next();
    }
};

function test (request,response,next) {
    response.send('Still alive');
};

However, when I try to do a GET to /rutas I'm not even getting a response. What am I doing wrong?

At server side I can see the following when I try it:

Error: Can't set headers after they are sent.

Solution

  • You can't call next() after sending a response, next() is meant to be called to pass the request/response to the next middleware in the stack. Consider this example:

    var app = require('express')();
    app.route('/rutas').get(sum, test);
    app.listen(function () { console.log(this.address()); });
    var i = 0;
    
    function sum (request, response, next) {
        i += 1;
        if (i % 2 === 0) {
            return response.status(200).end('Fin');
        }
        return next();
    }
    
    function test (request, response, next) {
        response.send('Still alive');
    }