【问题标题】:expressjs and module exports for routes with index带有索引的路由的 expressjs 和模块导出
【发布时间】:2017-05-17 17:41:09
【问题描述】:

我正在尝试使用 index.js 文件将我的路线导出到 express-app 中。

./app.js

const server = require('express'),
      app    = server(),
      port   = process.env.PORT

require('./routes/index')(app)
app.listen(port)

./routes/index.js

function routes(app) {
    require('./test')(app)
}
module.exports = routes

./routes/test.js

function test(app) {
    app.get('/', function (req, res) {
        console.info('test')
        res.end('Hello, World!')
    })
}

module.exports = test

当然,现在,当我执行 ./app.js 时,我收到一条错误消息,告诉我 require( ... ) is not a function on ./routes/index.js:2

但我似乎真的无法将我的大脑包裹在这个逻辑上。不是我错误的原因,而是如何在这个结构中将模块绑定在一起,同时将app 传递给模块。

这种结构背后的想法(如果不是很明显)是创建一个系统,可以通过在属于每个模块的索引文件中添加和删除模块来从应用程序中添加和删除模块,然后只需要每个模块集群的索引(例如路由)。

【问题讨论】:

    标签: node.js express module routes


    【解决方案1】:

    出于某种原因导出命名函数,如

    function someName(parameter) {
        require('./whatever')(parameter)
    }
    module.exports = someName
    

    不会工作...

    但是,导出匿名函数确实有效:

    module.exports = function (parameter) {
        require('./whatever')(parameter)
    }
    

    【讨论】:

    • 这真的很奇怪,因为它对我不起作用。节点-v 4.2.4
    • 您在问题中发布的文字代码在该特定版本的 Node.js 中运行良好。这真的是所有代码吗?
    • 一些(AFAIK)不应该影响问题的细微差异,但也许你可以告诉我? port 设置为 process.env.PORT || 1337,我正在配置应用程序以使用正文解析器。我还做了一个静态路由:app.use(server.static(__dirname + '/public', { maxAge: 1000 * 60 * 60 }))
    • 这不会是您遇到的问题,不。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-17
    • 2012-09-16
    • 2012-06-07
    • 1970-01-01
    • 1970-01-01
    • 2014-08-28
    • 2018-07-22
    相关资源
    最近更新 更多