简体   繁体   中英

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?

The problem is that router.use((req, res, next) => {...}) forces a middleware to be applied to entire router.

Middlewares aren't defined correctly here. As the manual states,

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application's request-response cycle. The next middleware function is commonly denoted by a variable named next.

While mA and mB are router instances that already have middlewares applied to them.

They should be:

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

next() is a function exposed by Express framework. Its not part of Nodejs but of Expressjs. as per express documentation "Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application's request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware."

Hope this helped you.

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM