我有很多充满样板代码的应用程序,如下所示:
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)
最佳答案
您可以指定多个中间件,参见the app.use docs :
An array of combinations of any of the above.
您可以创建所有中间件的文件,例如 -
middlewares.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'));
注意 - 仅对所有请求通用的中间件执行此操作
关于javascript - Express:我可以在一个app.use中使用多个中间件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52540548/