麻烦组织expressjs路线

时间:2012-12-03 00:32:49

标签: node.js routes express

我正在关注这个article,它描述了一种在快递中组织路线的好方法。我遇到一个问题虽然当我尝试访问我从main.js文件导出的函数。当我卷曲“localhost / user / username”

时,我收到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();
};

----用我的解决方案编辑----

这是我使用的解决方案,也许有人会发现它很有用。我也愿意听取关于这是否会在将来给我带来任何问题的建议。

//-------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();
    });

};

2 个答案:

答案 0 :(得分:2)

全球是邪恶的,应该不惜一切代价避免。以下是我如何组织没有全局变量且没有过多锅炉板代码的路线。

// 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
})

我想最后这是一个偏好问题,但如果你希望你的代码保持敏捷性并与其他模块一起工作,你应该避免使用全局变量。即使亚历克斯杨说它没关系。 =)

答案 1 :(得分:2)

这是我使用的解决方案,也许有人会发现它很有用。

//-------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();
    });

};