如果应用程序已经在监听,如何添加快速路线?
我想创build自动路由快递,目前我可以读取目录,并从所有可用的文件手动添加路由,添加的路由也可以更新如果有路由文件中的更改
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 + '\''); }
但是这些只是在应用程序收听端口之前才工作,
如何在应用程序侦听端口后添加/删除新的路由堆栈?
我可以想到的一种方法是closures服务器configuration/添加/删除重新听的路线,但我想这是一个不好的做法
我很愚蠢….
即使在听后,Express 4默认也可以添加路由
那么为什么我以前不能这样做呢? 因为在路由器层堆栈之上,我添加了error handling层堆栈,所以我之后添加的任何路由器层,都不会被请求到达,因为当请求被处理时,它将首先被error handling层捕获。
所以正确的方法如下:
-
我必须pipe理哪些索引是位于
app._router.stack
的error handling程序堆栈层,在这种情况下,它是在数组的最后一层 -
添加新路线,例如:使用
app.use("/something", function(req, res, next){ res.send("Lol") })
-
删除error handling程序层堆栈,并将其放在路由器堆栈数组的最后
// 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);
现在你已经准备好了。
用快递代码打了一遍后,我发现这个:
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
它的作品!
- 翡翠模板不按预期显示页面
- dynamic地将处理程序添加到快速路由function
- 通过NodeJS在stream式响应上的内存使用率高
- nodejitsu 400错误:ENOENT,打开'/opt/run/snapshot/package/images/tmp/72118-89rld0.png
- Node.js和underscore.js – 模板
- 如何实现WebRTC录制到Node.js服务器
- NodeJS ExpressJS Multer文件扩展名为小写
- Node / Express JS身份validation:除了Passport JS以外还有其他什么?
- 在将路由拆分成不同的文件/模块时,得到“ForbiddenError:无效的csrf令牌”