javascript - 自动从nodejs和express中的文件夹中请求 "controllers"

标签 javascript node.js express

我试图将所有文件包含在名为“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 文件中,你正在创建一个快速的“子应用程序”,将一个路由附加到它,然后不对其执行任何操作。

你应该:

  1. 将您的应用程序作为参数传递到 require 中,并将路由附加到您的原始 Express 应用程序
  2. 返回子应用或路由器,然后从主 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/

相关文章:

javascript - Node.js 启动时运行方法

Node.js Express 框架提供静态 swf 文件

javascript - Selenium - ElementNotVisibleException。元素在 Safari 9.1 中可见,但在 10.1 中不可见?

for循环中的javascript闭包

node.js - node.js 中的 Geojson 到 Topojson

javascript - 我应该在sequelize (node.js) 中使用转义字符串吗?

javascript - 通过 Javascript/Web 浏览器编码 MPEG 电影?

javascript - 为什么单击按钮后重新排序不起作用?

javascript - 如何停止 Node js-winston库中出现audit.json文件

angularjs - Nodejs 没有收到 POST 正文