diegoaguilar
diegoaguilar

Reputation: 8376

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.

Upvotes: 1

Views: 1437

Answers (2)

Olli K
Olli K

Reputation: 1760

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');
}

Upvotes: 2

Ben Fortune
Ben Fortune

Reputation: 32127

You need to call next() outside your if statement and also add a return to break out of the middleware's function scope if you don't want it to proceed. next() is basically saying, don't stop at this middleware, move onto the next one.

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

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

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

Upvotes: 1

Related Questions