[英]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.