代码之家  ›  专栏  ›  技术社区  ›  Christian Weisenburger

express.js-将路由导入子路由

  •  1
  • Christian Weisenburger  · 技术社区  · 6 年前

    我正在尝试构建一个具有良好结构的模块化Express.js服务器。 尝试使用不同的路径作为反应中的组件。

    索引文件

    var syncsingle = require('./XYZ/syncsingle');
    app.get('/sync', syncsingle);
    

    同步开关

    if ( ** cool things **){
        var one = require ('./XYZ/sync/one');
        app.use('/sync', one);
    }else{
        var two = require ('./XYZ/sync/two');
        app.use('/sync', two);
    }
    

    也许有人能帮我解决这个问题? 在一个.js和两个.js中编写的代码应该只在app.use(..)点导入/包含。(例如,在php中,include(“blaa.php”)的内容)。

    非常感谢<3

    1 回复  |  直到 6 年前
        1
  •  1
  •   AJcodez    6 年前

    尝试将中间件或子应用程序直接传递到主应用程序。

    // index.js
    var sync = require("./syncsingle.js")
    app.use("/sync", sync)
    
    // syncsingle.js
    if ( ** cool things **){
      module.exports = require ('./XYZ/sync/one');
    } else {
      module.exports = require ('./XYZ/sync/two');
    }
    

    将配置传递到子应用程序或中间件也是常见的。

    var one = require ('./XYZ/sync/one');
    var two = require ('./XYZ/sync/two');
    
    module.exports = function sync(options) {
      if ( ** cool things based on options ** ){
        return one;
      else {
        return two;
      }
    }
    

    在主应用程序文件中:

    app.use("/sync", sync({ useOne: true })