すべてのファイルをエクスプレスルートとその他のファイルを持つ "コントローラ"というディレクトリに含めるようにしています。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!');
});
おかげで、それは、私がやったことが、病気ですある場合は、 "クリーナー"ソリューションを見つけることを試みてください... –
たぶん[express routers](http://expressjs.com/es/api。html#router)はコントローラファイルをよりきれいにするのに役立ちますが、他のファイルは構造に依存します。 :) –
ありがとう、私はルータを使用し、それはずっときれいだ –