我试图将所有文件包含在名为“controllers”的目录中,该目录中包含带有快速路由的文件和其他一些内容。
问题是这些文件中定义的路由不起作用,但如果我将所有代码粘贴到索引文件(需要 Controller 的文件)中,它们就可以正常工作。
这是我的代码/文件:
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 );
});
controllers/index.js
const app = require('express')();
const debug = require('../config').debug;
app.get('/', (req, res) => {
res.send('Hello, World!');
});
最佳答案
在你的 Controller 文件中,你正在创建一个快速的“子应用程序”,将一个路由附加到它,然后不对其执行任何操作。
你应该:
- 将您的应用程序作为参数传递到 require 中,并将路由附加到您的原始 Express 应用程序
- 返回子应用或路由器,然后从主 Express 应用中安装/使用它
示例:
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);
});
}
controllers/index.js
const debug = require('../config').debug;
module.exports = app => {
app.get('/', (req, res) => {
res.send('Hello, World!');
});
}
关于javascript - 自动从nodejs和express中的文件夹中请求 "controllers",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39749470/