简体   繁体   English

你如何模块化Node.JS w / Express

[英]How do you modularize Node.JS w/Express

I'm trying to modularize my node.js application (using express framework). 我正在尝试模块化我的node.js应用程序(使用快速框架)。 The trouble I am having is when setting up my routes. 我遇到的麻烦是在设置我的路线时。

I am no longer able to extract the data I send to the post. 我无法再提取发送到帖子的数据。 (req.body is undefined). (req.body未定义)。 This works okay if it is all in the same file. 如果它们都在同一个文件中,则可以正常工作。 What am I doing wrong here, and what is the best way to modularize code in node.js? 我在这里做错了什么,在node.js中模块化代码的最佳方法是什么?

My app.js 我的app.js.

require('./routes.js').setRoutes(app);

My route.js 我的路线.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
      }
    });
});

A better approach: 更好的方法:

Create a routes.js file that contains: 创建包含以下内容的routes.js文件:

var index = require('./controllers/index');

module.exports = function(app) {
  app.all('/', index.index);
}

Then, from within your server.js (or however you've started your server), you'd require it as such: 然后,从您的server.js内部(或者您启动了服务器),您需要它:

require('./routes')(app);

This way you aren't creating global variables that bring with them a whole slew of issues (testability, collision, etc.) 这样你就不会创建全局变量,带来一大堆问题(可测试性,碰撞等)

I realize someone already answered but here's what I do anyway. 我意识到有人已经回答了,但无论如何我都是这样做的。

app.js : app.js:

fs.readdir('./routes', function(err, files){
    files.forEach(function(fn) {
        if(!/\.js$/.test(fn)) return;
        require('./routes/' + fn)(app);
    });
});

./routes/index.js : ./routes/index.js:

module.exports = function(app) {
        var data_dir = app.get('data-dir');

    app.get('/', function(req, res){
        res.render('index', {title: 'yay title'}
    });
}

Maybe someone will find this approach helpful. 也许有人会发现这种方法很有帮助。

My issue was that I was declaring app in the wrong way. 我的问题是我以错误的方式宣布应用程序。 Instead of var app = module.exports = express.createServer(); 而不是var app = module.exports = express.createServer(); , it should have just been app = express.createServer(); ,它应该刚刚app = express.createServer();

And then all I needed to do in my app.js was require('./routes.js'); 然后我需要在app.js中做的就是require('./routes.js'); . Now the routes file has access to the app variable and now I can just declare routes normally in the routes file. 现在,routes文件可以访问app变量,现在我可以在routes文件中正常声明路由。

(routes.js) (routes.js)

app.get('/test', function(req, res){
    console.log("Testing getter");
    res.writeHead('200');
    res.end("Hello World");
}); 

example in app.js app.js中的示例

var users = require('./lib/users'); //this is your own module
app.use(users);

then, you in your lib/users folder, create files ( index.js,user.ejs,etc). 然后,您在lib / users文件夹中创建文件(index.js,user.ejs等)。 use index.js for default module load //index.js var express = require('express'); 使用index.js进行默认模块加载//index.js var express = require('express'); var app = module.exports = express(); var app = module.exports = express();

app.set('views',__dirname);
app.set('view engine','ejs');
app.get('/users',function(req,res){
    //do stuffs here
});

I made an example of Modular node.jes + Boostrap here : Nodemonkey or a tutor here here 我做了模块化node.jes +自举在这里的一个例子: Nodemonkey或导师在这里在这里

global "app" for me (usually). 全球“app”对我来说(通常)。 If you know the app wont be require()d, and if you're not clumsy it's a lot easier to work with 如果您知道应用程序不会被要求()d,如果您不笨拙,那么使用它会容易得多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM