Alexander Mills
Alexander Mills

Reputation: 99960

Express middleware - router.use issue

I have this simple code:

var express = require('express');
var router = express.Router();

router.get('/', function (req, res, next) {


    req.lectalApiData = {
        Model: Email,
        conditions: req.query
    };

    router.use(function(req,res,next){    //this is not executing
        console.log('do that') 
        res.json({ok:'OK'});
    });

});

I clearly am doing something wrong, but according to the docs, it says I can use this syntax: http://expressjs.com/guide/routing.html

what am I doing wrong?

perhaps it's because the router.use is nested inside a router.get -

so my question then becomes - how do I create more middleware for that same route inside the router.get middleware?

Upvotes: 0

Views: 141

Answers (1)

Kevin B
Kevin B

Reputation: 95030

Just keep adding functions to router.get('/',, they get executed in order. Don't forget to call next.

router.get('/', function (req, res, next) {
    req.lectalApiData = {
        Model: Email,
        conditions: req.query
    };
    next(); // pass off to next middleware
}, function(req,res,next){
    console.log('do that') 
    res.json({ok:'OK'});
});

or better:

function doThis(req, res, next) {
    req.lectalApiData = {
        Model: Email,
        conditions: req.query
    };
    next(); // pass off to next middleware
}

function doThat(req, res) {
    console.log('do that') 
    res.json({ok:'OK'});
}

router.get('/', doThis, doThat);

Upvotes: 1

Related Questions