首页 > 解决方案 > 如何在 ExpressJS 中自动包含路由

问题描述

假设您一直想在路由上添加某些前缀,例如/before在文件中的某一行之后将其弹出server.js

这是一个例子

const express = require('express');
const App = express(); 

App.get('/before') //so here the route is '/before'

App.push('/after') //This is a made up method, but something like this has to exist...

App.get('/before') //And this route would be '/after/before'

App.pop(); //Another made up method

App.get('/before') //and this would be just "/before"

标签: node.jsexpressrouting

解决方案


这并不完全是.push()and.pop()设计,但它可以让您实现在公共父路径下分组路由的相同目标,而无需在每个路由定义上指定公共父路径。

Express 具有独立路由器的概念。您定义了一堆希望在路由器上共享公共父路径的路由。然后在路由器上注册每个叶路径,然后在父路径上注册整个路由器。

这是一个例子:

const express = require('express');
const app = express();

const routerA  = express.Router();

// define routes on the router
routerA.get("/somePath1", ...);
routerA.get("/somePath2", ...);
routerA.get("/somePath3", ...);

// hook the router into the server at a particular path
app.use("/parentPath", routerA);

app.listen(80);

这注册了三个路由:

/parentPath/somePath1    
/parentPath/somePath2    
/parentPath/somePath3    

推荐阅读