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

标签 javascript node.js express

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

index.js

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

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

关于javascript - Express.js - 将路由导入子路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53918585/

相关文章:

node.js - ExpressJS 中带有路径变量的链式路由

javascript - 从客户端 Web 浏览器与串行端口通信。

javascript - 如何在javascript中通过引用传递变量?从返回多个值的 ActiveX 函数中读取数据

javascript - 当前语言 angularjs 和 i18next

javascript - 在这个更高级别的函数中,参数 n 来自哪里?

Javascript ES6 类变量

node.js - Node : want to map domains to server

javascript - 表示下一个抛出错误,因为下一个未定义

node.js - BodyParser 已弃用

javascript - 拉维尔 | Javascript |在 Blade 中选择特定的 html 表