node.js - 如何在 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()
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
推荐阅读
- flutter - 使用 get API 获取 null 响应
- c - 我无法正确输入用户表单
- php - 如何修复“调用未定义函数”-PHP、mgp25
- linux - “ORA-29913:执行 ODCIEXTTABLEFETCH 标注时出错 ORA-29400:数据磁带错误”尝试在外部表上运行 Select Stmt 时
- php - 从txt文件获取数据到php的数组
- java - java.lang.IllegalArgumentException:未知实体:Model.Point
- angular - 如何在 .Net Core Web Api 中上传目录?
- flutter - Flutter - flutter-web 中的条件库导入
- mongodb - 多个聚合的性能不佳
- c - 基于链表的中缀计算器中的错误