我正在关注这篇文章,它描述了一种在 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();
});
};