快递:组成中间件 [英] Express: composing middleware

查看:92
本文介绍了快递:组成中间件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一系列app.use()调用移到其自己的模块中.封装此方法最简单的方法是在导出文件中公开function(app),但是我感觉交出app对象太不透明了.

I want to move a series of app.use() calls into its own module. The easiest way to encapsulate this is to expose a function(app) in the exports, but I feel that handing over the app object is too much of an opaque interface.

我想公开一个从模块外部app.use()的中间件.我需要链接/组成内部使用的中间件.

I would like to expose a middleware to be app.use()'d from outside the module. I need to chain/compose the middlewares used internally.

是否有一种时尚的方法或替代方法?最简单的方法是什么?我应该避免什么?

Is there a stylish way of doing this, or an alternative? What's the easiest way of going about it? Anything I should avoid?

推荐答案

这个答案有点晚了,但是无论如何这里都可以...

This answer is a little late, but here it goes anyway...

// composedMiddleware.js
const express = require('express')
const ware1 = (req, res, next)=>{...}
const ware2 = (req, res, next)=>{...}
const router = express.Router()
router.use(ware1)
router.use(ware2)
export default router

// app.js
const composedMiddleWare = require('./composedMiddleware.js')
app.get('/something', (req, res, next)=>{...})
app.get('/something', composedMiddleWare)

如果代码不是不言自明的,那么请注意路由器也是中间件.或者,更准确地说,路由器的行为类似于中间件本身,因此您可以将其用作app.use()的参数."

If the code isn't self-explanatory, then just note that routers are also middleware. Or, to put it more precisely, "a router behaves like middleware itself, so you can use it as an argument to app.use()" ref.

这篇关于快递:组成中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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