javascript - Express:我可以在一个app.use中使用多个中间件吗?

标签 javascript node.js express

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

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/

相关文章:

node.js - 使用 Sequelize 和 Postgres 从外键引用的另一个表中查询数据

session - Express.js + Passport.js : How to restrict multiple login by the same user?

javascript - 在 NodeJS 中测试对象相等性

javascript - 更改 innerHTML 属性时处理程序会发生什么

node.js - 将 node_modules 安装到 vendor

node.js - 使用 NodeJS 和 ObjectionJs 进行分页查询

node.js - .env 使用 vscode 和 dotenv npm 调试断点

javascript - 通过 Express/Node.js 中的重定向将错误消息传递给模板

javascript - 多个 <select/> 与 KnockoutJS 链接,依赖项存储在数据库中

javascript - 在nodejs中使用异步配置sequelize