假设您总是想在路由上添加某些前缀,例如/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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句