Express: can I use multiple middleware in a single app.use?

浪尽此生 提交于 2020-01-17 02:14:05

问题


I have a lot of apps full of boilerplate code that looks like this:

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());

How can I use multiple middleware at once? So I could turn the above into:

// 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)

回答1:


You can specify multiple middlewares, see the app.use docs:

An array of combinations of any of the above.

You can create a file of all middlewares like -

middlewares.js

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

and as then simply add it like:

/*
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'));

Note - Do this only for those middlewares which will be common for all requests




回答2:


I like to use a Router to encapsulate application routes. I prefer them over a list of routes because a Router is like a mini express application.

You can create a body-parsers router like so:

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;

Then attach it to your main application like any other route:

const express = require('express');

const app = express();
app.use(require('./body-parsers'));



回答3:


Try it like this, in main app.js run just init code:

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

And then in bodyParserInit you can do app.use

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


来源:https://stackoverflow.com/questions/52540548/express-can-i-use-multiple-middleware-in-a-single-app-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!