[英]How to add express route if the app already listening?
我想在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 + '\'');
}
但这些仅在应用程序侦听端口之前有效,
应用侦听端口后如何添加/删除新的路由堆栈?
我能想到的一种方法是关闭服务器配置/添加/删除重新监听的路由,但我想这是一个不好的做法
在使用快速代码后,我发现了这个:
router.get('/', function(req, res) {
res.render('index', {
title: 'Express'
});
console.log("adding route")
addGet('/mypath', function(req, res) {
res.send('hi')
});
});
function addGet(path, callback) {
Router = require('express').router;
// We get a layer sample so we can instatiate one after
layerSample = router.stack[0];
// get constructors
Layer = layerSample.constructor;
Route = layerSample.route.constructor;
// see https://github.com/strongloop/express/blob/4.x/lib/router/index.js#L457
route = new Route(path);
var layer = new Layer(path, {
sensitive: this.caseSensitive,
strict: this.strict,
end: true
}, route.dispatch.bind(route));
layer.route = route;
// And we bind get
route.get(callback)
// And we map it
router.stack.push(layer);
}
那么然后在localhost
打开你的浏览器,然后在localhost/mypath
打开你的浏览器!
我太蠢了......
Express 4默认即使在收听后也可以添加路由
那么为什么我以前不能这样做呢? 因为在路由器层堆栈之上,我添加了错误处理层堆栈,因此我在其后添加的任何路由器层都不会被请求访问,因为当处理请求时,它将首先由错误处理程序层捕获。
所以正确的方法如下:
我必须管理位于app._router.stack
的错误处理程序堆栈层的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);
现在你准备好了。
七年后,我和 DeckyFx 有同样的疑问。
我需要在启动时设置快速堆栈,然后动态加载具有自己的路由器的“插件”。
因此,在阅读了当前的快速文档并没有找到任何处理堆栈层的方法后,我根据此处阅读的不同答案集成了我自己的方法
很简单:
我的代码:
// static tail layers definition
_tailLayers = ['UnknownRouteHandler','ErrorRouteHandler'];
// delete tail layer with filter
app._router.stack = app._router.stack.filter(layer => !_tailLayers.includes(layer?.name));
// inject new route
app.use('/', MyRouter);
// inject again stack tail
app.use(UnknownRouteHandler);
app.use(ErrorRouteHandler);
其作品!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.