简体   繁体   English

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

[英]Express.js - Import routes into subroute

I'm trying to build an modular express.js server with a good structure.我正在尝试构建一个具有良好结构的模块化 express.js 服务器。 Tryed to use the different routes as the components in react.尝试使用不同的路线作为反应中的组件。

index.js索引.js

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

syncsingle.js同步单.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);
}

Maybe someone could help me out with that issue?也许有人可以帮我解决这个问题? The code which is written in one.js and two.js should be just imported/included at the app.use(..) point.用 one.js 和 two.js 编写的代码应该只在 app.use(..) 点导入/包含。 (eg in PHP the include('blaa.php') thing). (例如在 PHP 中的 include('blaa.php') 东西)。

Thank you very much <3非常感谢<3

Try passing the middleware or sub-app directly to your main app.尝试将中间件或子应用程序直接传递给您的主应用程序。

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

It's also common to pass configuration to sub-apps or middleware.将配置传递给子应用程序或中间件也很常见。

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;
  }
}

In your main app file:在您的主应用程序文件中:

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

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

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