麻烦组织expressjs路线

我正在跟随这篇文章 ,这篇文章描述了一种快速组织路线的好方法。 我遇到一个问题,虽然当我尝试访问我从我的main.js文件导出的函数。 当我curl“本地主机/用户/用户名”时,我得到一个404错误

//the routes section of my my app.js file app.get('/', routes.index); app.get('/user/:username', routes.getUser); //my index.js file require('./main'); require('./users'); exports.index = function(req, res) { res.render('index', {title: 'Express'}); }; //my main.js file exports.getUser = function(req, res){ console.log('this is getUser'); res.end(); }; 

—-编辑我的解决scheme—-

这是我一起去的解决scheme,也许有人会觉得它有用。 我也很乐意听取有关今后是否会给我带来什么问题的build议。

 //-------The routes in my app.js file now look like this. require('./routes/index')(app); require('./routes/main')(app); //-------In index.js i now have this module.exports = function(app) { app.get('/', function(req,res){ res.render('index', {title: 'Express'}); }); }; //-------My main.js now looks like this------- module.exports = function(app){ app.get('/user/:username', function(req, res){ var crawlUser = require('../engine/crawlUser'); var username = req.params.username; crawlUser(username); res.end(); }); }; 

全球化是邪恶的,不惜一切代价避免。 这里是我如何组织我的路线没有全局和没有过多的锅炉板代码。

 // File Structure /app.js /routes /--index.js /--main.js /--users.js // app.js var app = require('express'); /* Call Middleware here */ require('routes')(app); app.listen(3000); --------------------------------------------- // routes/index.js - This is where I store all my route definitions // in a long list organized by comments. Allows you to only need to go to // one place to edit route definitions. module.exports = function(app) { var main = require('./main'); app.get('/', main.get); var users = require('./users'); app.get('/users/:param', users.get); ... } --------------------------------------------- // routes/main.js - Then in each submodule you define each function and attach // to exports exports.get = function(req, res, next){ // Do stuff here }) 

我想最后是一个优先select的问题,但是如果你希望你的代码保持敏捷性并且和其他模块一起工作,你应该避免使用全局variables。 即使Alex Young说好。 =)

这是我一起去的解决scheme,也许有人会觉得它有用。

 //-------The routes in my app.js file now look like this. require('./routes/index')(app); require('./routes/main')(app); //-------In index.js i now have this module.exports = function(app) { app.get('/', function(req,res){ res.render('index', {title: 'Express'}); }); }; //-------My main.js now looks like this------- module.exports = function(app){ app.get('/user/:username', function(req, res){ var crawlUser = require('../engine/crawlUser'); var username = req.params.username; crawlUser(username); res.end(); }); };