繁体   English   中英

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

[英]Express.js - Import routes into subroute

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

索引.js

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

同步单.js

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

也许有人可以帮我解决这个问题? 用 one.js 和 two.js 编写的代码应该只在 app.use(..) 点导入/包含。 (例如在 PHP 中的 include('blaa.php') 东西)。

非常感谢<3

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

// 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 })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM