快递:我可以在一个app.use中使用多个中间件吗? [英] Express: can I use multiple middleware in a single app.use?

查看:338
本文介绍了快递:我可以在一个app.use中使用多个中间件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多应用程序,都充满了样板代码,如下所示:

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)

推荐答案

您可以指定多个中间件,请参见该app.use文档:

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

这篇关于快递:我可以在一个app.use中使用多个中间件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆