如何为所有节点/快速路由添加前缀 [英] How to add prefix to all node / express routes
问题描述
有谁知道一种配置express以在所有路由之前自动添加前缀的方法?例如,目前我有:
Does anyone know of a way to configure express to add a prefix before all routes automatically? for example, currently I have:
/
/route1
/route2
但是,我想添加一个前缀,如:
However, I want to add a prefix like:
/prefix/
/prefix/route1
/prefix/route2
现在我需要为我的所有路由手动定义 prefix
但想要更自动化/可配置的方式.有人可以帮忙吗?
Right now I need to define prefix
manually to all of my routes but would like a more automated/configurable way. Can someone help?
提前致谢!
推荐答案
您可以为此使用 express Router().
You can use the express Router() for this.
您可以像使用 Express 应用程序一样使用路由器.例如:
You can use the router like you would use your express app. So for example:
router.use(() => {}); // General middleware
router.get('/route1', () => {})
router.get('/route2', () => {})
router.post('/route2', () => {})
然后使用以下命令将路由器连接到您的 Express 应用程序:
And then attach the router to your express app using:
app.use('/prefix', router);
https://expressjs.com/en/4x/api.html#router
这篇关于如何为所有节点/快速路由添加前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!