问题描述
有人知道如何配置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
这篇关于如何在所有节点/快速路由中添加前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!