我有一个这样的应用程序:
import express from 'express';
const middleware = tag => (req, res, next) => {
console.log('middleware ' + tag);
next();
};
const app = express();
const router = express.Router();
router.use(middleware('a'));
router.get('/x', (req, res) => res.json({ message: 'x' }));
app.use(router);
app.use(middleware('b'));
app.get('/y', (req, res) => res.json({ message: 'y' }));
app.use(middleware('c'));
app.listen(3000);
但是,Router
的行为并不符合我的预期:
$ curl localhost:3000/x
middleware a
$ curl localhost:3000/y
middleware a
middleware b
为什么点击/y
会调用中间件?我以为中间件只适用于router
。
如何将中间件仅应用于 router
,而不应用于 app
中的其他路由?
最佳答案
即使您是通过路由器完成的,因为您随后连接的路由器没有子路径,所以它会将所有内容捆绑在一起。在您的示例中,您已将所有内容附加到同一父端点 /
,因此即使它是通过路由器完成的,您也会将此路由器附加到 /
路径。
如果您只想按照您的指示将中间件分开,那么您有两个选择。
将端点子路径设置为
/feature1/x
和/feature2/y
等。将中间件分别附加到/feature1
和/feature2
。这会给你想要的结果。这可以通过以下方式连接端点/x
的路由器来完成:app.use('/feature1', router);
这意味着您现在拥有端点 /feature1/x
和 /y
。每次触发其独立的中间件链。
将中间件附加到特定端点,例如:
app.get('/x, middleware('a'), (req, res) => res.json({message: 'x'}); app.get('/y', middleware('b'), (req, res) => res.json({message: 'y'});
您目前所做的是将所有内容附加到同一路由路径(在本例中为顶级斜杠 /
)。
关于javascript - 表达中间件困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50061062/