1

我正在关注这篇文章,它描述了一种在 express 中组织路线的好方法。但是,当我尝试访问从 main.js 文件中导出的函数时,我遇到了一个问题。curl "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();
    });

};
4

2 回答 2

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

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

于 2012-12-03T00:58:32.067 回答
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();
    });

};
于 2012-12-07T06:37:20.083 回答