Kir*_*ali 13 javascript node.js express
我正在尝试模块化我的node.js应用程序(使用快速框架).我遇到的麻烦是在设置我的路线时.
我无法再提取发送到帖子的数据.(req.body未定义).如果它们都在同一个文件中,则可以正常工作.我在这里做错了什么,在node.js中模块化代码的最佳方法是什么?
我的app.js.
require('./routes.js').setRoutes(app);
Run Code Online (Sandbox Code Playgroud)
我的路线.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
}
});
});
Run Code Online (Sandbox Code Playgroud)
cti*_*ide 30
更好的方法:
创建包含以下内容的routes.js文件:
var index = require('./controllers/index');
module.exports = function(app) {
app.all('/', index.index);
}
Run Code Online (Sandbox Code Playgroud)
然后,从您的server.js内部(或者您启动了服务器),您需要它:
require('./routes')(app);
Run Code Online (Sandbox Code Playgroud)
这样你就不会创建全局变量,带来一大堆问题(可测试性,碰撞等)
归档时间: |
|
查看次数: |
10761 次 |
最近记录: |