代码之家  ›  专栏  ›  技术社区  ›  mikemaccana

我可以在一个应用程序中使用多个中间件吗?

  •  0
  • mikemaccana  · 技术社区  · 6 年前

    我有很多应用程序都是这样的样板代码:

    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(cookieParser());
    app.use(require('express-session')({
            secret: 'keyboard cat',
            resave: false,
            saveUninitialized: false
    }));
    app.use(passport.initialize());
    app.use(passport.session());
    

    // Some file, exporting something that can be used by app.use, that runs multiple middlewares
    const bodyParsers = require('body-parsers.js')
    const sessions= require('sessions.js')
    
    // Load all bodyparsers
    app.use(bodyParsers)
    
    // Load cookies and sessions
    app.use(sessions)
    
    3 回复  |  直到 6 年前
        1
  •  15
  •   mikemaccana    6 年前

    您可以指定多个中间件,请参阅 the app.use docs :

    上述任意一种组合的数组。

    中间件.js

    module.exports = [
      function(req, res, next){...},
      function(req, res, next){...},
      function(req, res, next){...},
      .
      .
      .
      function(req, res, next){...},
    ]
    

    然后简单地加上:

    /*
    you can pass any of the below inside app.use()
    A middleware function.
    A series of middleware functions (separated by commas).
    An array of middleware functions.
    A combination of all of the above.
    */
    app.use(require('./middlewares.js'));
    

    注意-只对那些对所有请求都通用的中间件执行此操作

        2
  •  5
  •   Jake Holzinger    6 年前

    我喜欢使用 Router 封装应用程序路由。我更喜欢它们而不是路线列表,因为 路由器 就像一个迷你快递应用程序。

    您可以创建 body-parsers

    const {Router} = require('express');
    
    const router = Router();
    
    router.use(bodyParser.json());
    router.use(bodyParser.urlencoded({ extended: false }));
    router.use(cookieParser());
    router.use(require('express-session')({
            secret: 'keyboard cat',
            resave: false,
            saveUninitialized: false
    }));
    router.use(passport.initialize());
    router.use(passport.session());
    
    module.exports = router;
    

    然后像其他任何途径一样将其附加到主应用程序:

    const express = require('express');
    
    const app = express();
    app.use(require('./body-parsers'));
    
        3
  •  0
  •   Ivan Marjanovic    6 年前

    像这样尝试,在main app.js中运行init代码:

    const bodyParserInit = require('./bodyParserInit');
    ....
    bodyParserInit(app);
    

    module.exports = function (app) {
      app.use(bodyParser.json());
      app.use(bodyParser.urlencoded({ extended: false }));
    }