lundi 23 juillet 2018

Node.js multiple middleware export pattern

I use Nodejs, Expressjs and
I dont understand how exactly work next() in middleware

middleware/myMiddleware.js

const { Router } = require('express');
const router = Router();

module.exports = {
  mA: router.use((req, res, next) => {
    console.log('a');
    next();
  }),
  mB: router.use((req, res, next) => {
    console.log('b');
    next();
  }),
};

routes/myRoute.js

const { mA, mB } = require('../middlewares/myMiddleware');
router.get('/welcome'
  , mA
  ,(req, res) => res.render('welcome'));
router.get('/welcome2'
  , mB
  ,(req, res) => res.render('welcome2'));
module.exports = router;

This should work like this
welcome -> log a
welcome2 -> log b

but it works
welcome -> log a, log b
welcome2 -> log a, log b
why?
And how can I fix it? is this bad design?




Aucun commentaire:

Enregistrer un commentaire