Javascript 如果应用程序已在侦听,如何添加快速路线?

Javascript 如果应用程序已在侦听,如何添加快速路线?,javascript,node.js,express,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:

我想在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 + '\'');
}
但这些只有在应用程序侦听端口之前才能工作

如何在应用程序侦听端口后添加/删除新路由堆栈


我可以想到的一种方法是关闭服务器,配置/添加/删除重新侦听的路由,但我猜这是一种不好的做法

在使用express代码四处搜索之后,我发现:

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 default即使在侦听之后也可以添加路由

那为什么我以前不能做呢?因为在路由器层堆栈的顶部,我添加了错误处理层堆栈,所以我在它之后添加的任何路由器层都不会被请求访问,因为当处理请求时,错误处理层会首先捕获它

因此,正确的方法如下所示:

  • 我必须管理错误处理程序堆栈层的索引 位于
    app.\u router.stack
    中,在本例中,它位于 数组的最末端

  • 添加新路由,例如:使用
    app.use(“/something”),函数(req,
    res,next){res.send(“Lol”)})

  • 移除错误处理程序层堆栈,并将其置于 路由器堆栈阵列的最末端

    //在这种情况下,错误映射是数组
    //包含错误处理堆栈层的索引位置
    var error\u handlers=app.\u router.stack.splice(error\u map[0],error\u map.length);
    app.\u router.stack.push.apply(app.\u router.stack,错误处理程序)


  • 现在您可以开始了。

    您要添加什么样的路由?它可以获取、发布、放置或删除express的哪个版本?json包说它是“express”:“~4.2.0”,我应该降低它吗?顺便说一句,我更新了我的代码块