简体   繁体   English

如何在ExpressJS中正确组织路线?

[英]How to properly organize routes in ExpressJS?

I'm developing my first test application on NodeJS and encountered the following problem: i can't figure out how to properly organize routes in ExpressJS framework. 我在NodeJS上开发了我的第一个测试应用程序,遇到了以下问题:我不知道如何在ExpressJS框架中正确组织路由。 For example i want to do registration, so i create route like: 例如,我想进行注册,因此我创建如下路线:

app.get('/registration', function (request, response) {
    if (request.body.user.email && request.body.user.password) {
        var user = new User();
        var result = user.createNew(request.body.user.email, request.body.user.email);

        // do stuff...
    }

    response.render('registration.html', config);
});

User function looks like this (not the final): 用户功能看起来像这样(不是最终的):

function User() {
    var userSchema = new mongoose.Schema({ 
        'email': { 
            'type': String, 
            'required': true, 
            'lowercase': true, 
            'index': { 'unique': true }
        },
        'password': {
            'type': String, 
            'required': true
        }
    });

    var userModel = mongoose.model('users', userSchema);

    this.createNew = function(email, password) {
        var new_user = new users({'email': email, 'password': password});

        new_user.save(function(err){
            console.log('Save function');

            if (err)
                return false;

            return true;
        });
    }
}

I try to do a bit of structured applications like MVC. 我尝试做一些像MVC这样的结构化应用程序。 The problem is that the save method is asynch and each time i registrate new user get registration.html without waiting for the result. 问题是save方法是异步的,每次我让新用户registration.html都会获取registration.html而无需等待结果。

Basically i need to run route callback in save callback, but how to do this in the right way i can't figure out by myself... 基本上我需要在save回调中运行路由回调,但是如何以正确的方式执行此操作,我自己无法弄清楚...

this.createNew = function(email, password, callback) {
    var new_user = new users({'email': email, 'password': password});

    new_user.save(function(err){
        console.log('Save function');

        if (err)
            // return false;
            callback (false);
        else
            //return true;
            callback (true);
    });
}

I find that whenever I'm using some module (db for example) and it's using a callback, I will often have to also use a callback for any function I wrap around it (unless I don't care about the results). 我发现,每当我使用某个模块(例如db)并且使用回调时,对于包裹的任何函数,我通常都必须使用回调(除非我不在乎结果)。

Here: 这里:

app.get('/registration', function (request, response) {
    if (request.body.user.email && request.body.user.password) {
        var user = new User();
        // var result = user.createNew(request.body.user.email, request.body.user.email);

        user.createNew(request.body.user.email, request.body.user.email, function (results) {
             // do something with results (will be true or false)
             // not sure why you have this with the actual registration stuff,
             // but it's your site. :)
             response.render('registration.html', config);
        });
    }
});

Also, you might want to put your object methods in the prototype, instead of: 另外,您可能希望将对象方法放在原型中,而不是:

this.createNew = function (....) {}

Try: 尝试:

User.prototype.createNew = function ( ... ) { }

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures#Performance_considerations for info on why. https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Closures#Performance_considerations了解有关原因的信息。

For a starting point on organising your Node.js app, try reading through the source code on this demo express.js app. 有关组织Node.js应用程序的起点,请尝试通读此demo express.js应用程序上的源代码。 Click here for the link 点击这里链接

It's a fairly popular repo, which I often find myself referencing when building Node.js apps from scratch. 这是一个相当受欢迎的仓库,当我从头开始构建Node.js应用程序时,我经常会发现自己在引用它。

It may be a good reference for your project given it's done in an the MVC style and it uses mongoose. 鉴于它以MVC样式完成并且使用猫鼬,因此它可能是对您的项目的很好参考。 The routes are organised into a single file which can be found in config/routes.js . 路由被组织到一个文件中,该文件可以在config/routes.js找到。 You should also take a look at the models in app/models/ for an alternative way to organise your user model 您还应该查看app/models/中的app/models/ ,以另一种方式来组织用户模型

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

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