javascript - 高速路由器

标签 javascript node.js express

我正在 NodeJS 上开发内容预处理器 我有3种具体的预处理方法:

  • 构建 html
  • 构建 xhtml
  • 构建 xml

每种方式彼此都有很大不同(不同的中间件) 所以我初始化了3个路由器:

  var xmlRouter = express.Router();
  var xhtmlRouter = express.Router();
  var htmlRouter = express.Router();

我需要的只是将每个请求分派(dispatch)到具体的路由器。 我无法使用 app.use() 来安装每个路由器,因为对我的 url 产生剥离效果:

// Binding
app.use(/\/\S*\.fast\.xml(?=$)/, xmlRouter);
app.use(/\/\S*\.xhtml(?=$)/, xhtmlRouter);
app.use([/\/\S*\.html(?=$)/, /\/\S*\/(?=$)/], htmlRouter);

我将失去我需要进一步了解的网址。没办法

那么有什么解决办法吗?

最佳答案

我现在无法测试它,但由于它不适合评论,所以我将其写在答案部分。

恕我直言,它应该这样工作:

var xmlRouter = express.Router();
app.use(function(req, res, next) {
   if( req.url.match(/\/\S*\.fast\.xml(?=$)/) ) {
      //if the url matches, pass the res, res, next to the xmlRouter
      xmlRouter.handle(req, res, next); 
      //if handle does not work try: xmlRouter(req, res, next)
   } else {
      //otherwise pass it to the next registered route
      next();
   }
});

//do the same for the other routers

也许这个示例有错误,因为我无法测试它,但我认为这个想法应该很清楚。

关于javascript - 高速路由器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35655477/

相关文章:

JavaScript this 来自 jQuery this

javascript - Express res.redirect 不重定向

node.js - 使用不是 Sequelize.Model 子类的东西调用的 Sequelize 关联

javascript - 测试监听 stdin.isTTY 的 Node CLI 工具?

angularjs - 如何通过 Express 路由到多个 Angular 应用程序?

node.js - 为什么我的异步代码在 Controller 中有效,而在模型中无效?

javascript - 从它的 Html 字符串或转换的 jQuery 对象中查找 Ajax error.ResponseText 的标题/任何标签

javascript - 尝试动态创建也可以关闭的div

javascript - 如何通过几个函数计算一个简单的方程? (DOM)

Javascript,instanceof 函数的行为