Dec*_*yFx 5 javascript node.js express
我想在express中创建自动路由,目前我可以读取目录并手动从所有可用文件添加路由,如果路由文件中有更改,也可以更新添加的路由
delete require.cache[require.resolve(scriptpath)];
var routescript = {};
try {
routescript = require(scriptpath);
} catch (e){
console.log('Express >> Ignoring error route: ' + route + ' ~ >' + scriptpath);
}
var stack_index = app._router.stack_map[route]
var stack = app._router.stack[stack_index];
if (stack) {
app._router.stack[stack_index].handle = routescript;
console.log('Replace Route Stack \'' + route + '\'');
} else {
app.use(route, routescript);
var stack_index = app._router.stack_map[route] = (app._router.stack.length-1);
console.log('Add Route Stack \'' + route + '\'');
}
Run Code Online (Sandbox Code Playgroud)
但那些只在app听端口之前才工作,
如何在应用程序侦听端口后添加/删除新的路由堆栈?
我能想到的一种方法是关闭服务器配置/添加/删除重听的路由,但我想这是一个不好的做法
我真是太傻了......
Express 4 默认情况下即使在监听后也能够添加路由
那为什么我之前做不到呢?因为在路由器层堆栈的顶部,我添加了错误处理层堆栈,所以我在其之后添加的任何路由器层都无法通过请求访问,因为当处理请求时,它将首先被错误处理程序层捕获。
所以正确的方法如下:
我必须管理错误处理程序堆栈层位于哪个索引app._router.stack
,在本例中它是数组最末尾的某个层
添加新路线,例如:使用app.use("/something", function(req,
res, next){ res.send("Lol") })
删除错误处理层堆栈,并将其放在路由器堆栈数组的最末尾
// in this case, error map is array
// contain index location of error handling stack layer
var error_handlers = app._router.stack.splice(error_map[0], error_map.length);
app._router.stack.push.apply(app._router.stack, error_handlers);
现在您已准备好出发了。
归档时间: |
|
查看次数: |
912 次 |
最近记录: |