如何在 ExpressJS 中自动包含路由

How to automatically include routes in 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"

这不完全是 .push().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