Wednesday 24 May 2017

ExpressJS 4 middleware problems

I'm trying to wrap my head arround the middleware in ExpressJS 4.

If I understood correctly is that middleware are applied in the order of declaration and that you can "bind" them at different level.

Here I'm trying to bind a middleware at router level.

function middleware(req, res, next) {
  console.log("middleware");
  res.write("middleware");
  next();
}
function handler(req, res) {
 console.log("OK");
 res.status(200).send('OK');
}

const router1 = express.Router();
const router2 = express.Router();

router1.get("/1", handler);
router2.get("/2", handler);

I would except the following to print OK when calling /test/1 and middleware on /test/2.

app.use("/test/", router2.use(middleware), router1);

But the output seems to be inverted and is equivalent to:

app.use("/test/", router2, middleware, router1);

What I really want is that only the first router to use the middleware. In other word scope the use of the middleware to the first controller.

I could easily swap the order of router1 and router2 but my other requirement is because my router2 use in fact a route that catch all requests (/:id) I need to have it last.

What I'm missing here and how can I do what I want ?



via Bit-Doctor

No comments:

Post a Comment