簡體   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