Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 带有索引的路由的expressjs和模块导出_Node.js_Express_Module_Routes - Fatal编程技术网

Node.js 带有索引的路由的expressjs和模块导出

Node.js 带有索引的路由的expressjs和模块导出,node.js,express,module,routes,Node.js,Express,Module,Routes,我正试图用index.js文件在一个express应用程序中导出我的路线 /app.js const server = require('express'), app = server(), port = process.env.PORT require('./routes/index')(app) app.listen(port) function routes(app) { require('./test')(app) } module.expo

我正试图用index.js文件在一个express应用程序中导出我的路线

/app.js

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

require('./routes/index')(app)
app.listen(port)
function routes(app) {
    require('./test')(app)
}
module.exports = routes
function test(app) {
    app.get('/', function (req, res) {
        console.info('test')
        res.end('Hello, World!')
    })
}

module.exports = test
/routes/index.js

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

require('./routes/index')(app)
app.listen(port)
function routes(app) {
    require('./test')(app)
}
module.exports = routes
function test(app) {
    app.get('/', function (req, res) {
        console.info('test')
        res.end('Hello, World!')
    })
}

module.exports = test
/routes/test.js

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

require('./routes/index')(app)
app.listen(port)
function routes(app) {
    require('./test')(app)
}
module.exports = routes
function test(app) {
    app.get('/', function (req, res) {
        console.info('test')
        res.end('Hello, World!')
    })
}

module.exports = test
当然,现在当我执行./app.js时,我得到一个错误,告诉我,
require(…)不是./routes/index.js:2上的函数

但我似乎真的无法理解这个逻辑。不是我出错的原因,而是如何在此结构中将模块绑定在一起,同时将
app
传递给模块


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

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

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

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

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

这真的很奇怪,因为这对我来说不起作用。Node-v 4.2.4您在问题中发布的文字代码在特定版本的Node中运行良好。这真的是所有的代码吗?一些微小的差异(AFAIK)不应该影响问题,但也许你可以告诉我<代码>端口
设置为process.env.port | | 1337,我正在配置应用程序以使用主体解析器。我还做了一个静态路由:
app.use(server.static(\uu dirname+'/public',{maxAge:1000*60*60}))
这不会解决您遇到的问题,不会。