我正在尝试模块化我的 node.js 应用程序(使用 express 框架)。我遇到的麻烦是设置路线时。
我不再能够提取我发送到帖子的数据。 (req.body 未定义)。如果它们都在同一个文件中,这可以正常工作。我在这里做错了什么,在 node.js 中模块化代码的最佳方法是什么?
我的 app.js
require('./routes.js').setRoutes(app);
我的路由.js
exports.setRoutes = function(app){
app.post('/ask', function(req, res, next){
time = new Date();
var newQuestion = {title: req.body.title, time: time.getTime(), vote:1};
app.questions.push(newQuestion);
res.render('index', {
locals: {
title: 'Questions',
questions: app.questions
}
});
});
最佳答案
更好的方法:
创建一个 routes.js 文件,其中包含:
var index = require('./controllers/index');
module.exports = function(app) {
app.all('/', index.index);
}
然后,在你的 server.js 中(或者你已经启动了你的服务器),你需要它:
require('./routes')(app);
通过这种方式,您不会创建会带来一系列问题(可测试性、碰撞等)的全局变量
关于javascript - 你如何模块化 Node.JS w/Express,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5055853/