2016-09-28 5 views
0

すべてのファイルをエクスプレスルートとその他のファイルを持つ "コントローラ"というディレクトリに含めるようにしています。nodejs内のフォルダから自動的に "コントローラ"を要求する

問題は、それらのファイル内で定義されたルートが機能していないことですが、インデックスファイル(コントローラが必要なファイル)にすべてのコードを貼り付けるとうまく動作します。

ここに私のコード/ファイルです:

index.js

// Expressjs 
const app = require('express')(); 

// Load and initialize the controllers. 
require('./lib/controllersLoader'); 

/* 
* Initializing the listener according to the settings in the config. 
*/ 
app.listen(3000, err => { 
    // Throwing an exception since the whole app depends on this. 
    if (err) throw err; 
    console.log(`SERVER: Running on port ${config.server.port}`); 
}); 

のlib/controllersLoader.js

const fs = require('fs'); 

// Getting an Array of the files in the 'controllers' folder. 
let files = fs.readdirSync(__dirname + '/../controllers'); 

files.forEach(fileName => { 
    require(__dirname + '/../controllers/' + fileName); 
}); 

コントローラ/ index.js

は、
const app = require('express')(); 
const debug = require('../config').debug; 

app.get('/', (req, res) => { 
    res.send('Hello, World!'); 
}); 

答えて

0

お使いのコントローラファイルの中に、あなたは特急「subappを作成していますそれにルートをつけて、何もしないでください。

あなたがする必要があります

  1. が必要でパラメータとしてあなたのアプリを渡し、そしてあなたの元急行アプリ
  2. 戻りsubapp、またはルータへのルートを添付し、そしてそれはあなたの主な特急から使用/マウントアプリ



index.js

// Expressjs 
const app = require('express')(); 

// Load and initialize the controllers. 
require('./lib/controllersLoader')(app); 

のlib/controllersLoader.js

const fs = require('fs'); 

// Getting an Array of the files in the 'controllers' folder. 
let files = fs.readdirSync(__dirname + '/../controllers'); 

module.exports = app => { 
    files.forEach(fileName => { 
     require(__dirname + '/../controllers/' + fileName)(app); 
    }); 
} 

コントローラ/ index.js

const debug = require('../config').debug; 

module.exports = app => { 
    app.get('/', (req, res) => { 
     res.send('Hello, World!'); 
    }); 
} 
+0

おかげで、それは、私がやったことが、病気ですある場合は、 "クリーナー"ソリューションを見つけることを試みてください... –

+0

たぶん[express routers](http://expressjs.com/es/api。html#router)はコントローラファイルをよりきれいにするのに役立ちますが、他のファイルは構造に依存します。 :) –

+0

ありがとう、私はルータを使用し、それはずっときれいだ –

0

私はあなたが新しいExpressインスタンスにあなたがこのようにそれを必要としているたびに初期化していると思う:

const app = require('express')(); 

あなたが唯一の急行インスタンスを使用して、コントローラにそれを渡すことができますか?そのような 何か:

module.exports = function(app){ 

    app.get('/', (req, res) => { 
     res.send('Hello, World!'); 
    }); 
} 

し、それらを呼び出すために:

require(__dirname + '/../controllers/' + fileName)(app); 

あなたの問題は、この1と非常によく似ているようだ:https://stackoverflow.com/a/6059938/734525

関連する問題