如何在所有节点/快速路由中添加前缀 [英] How to add prefix to all node / express routes

查看:674
本文介绍了如何在所有节点/快速路由中添加前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道如何配置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屋!

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