我有很多充满样板代码的应用,如下所示:
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)
答案 0 :(得分:2)
您可以指定多个中间件,请参见the app.use docs:
上述任何一项的组合数组。
您可以创建所有中间件的文件,例如-
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'));
注意-仅对所有请求通用的中间件执行此操作
答案 1 :(得分:1)
我喜欢使用Router
来封装应用程序路由。我更喜欢它们而不是路由列表,因为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'));
答案 2 :(得分:0)
像这样尝试,在主app.js中仅运行初始化代码:
const bodyParserInit = require('./bodyParserInit');
....
bodyParserInit(app);
然后在bodyParserInit中,您可以执行app.use
module.exports = function (app) {
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
}