簡體   English   中英

如何在ExpressJS中正確組織路線?

[英]How to properly organize routes in ExpressJS?

我在NodeJS上開發了我的第一個測試應用程序,遇到了以下問題:我不知道如何在ExpressJS框架中正確組織路由。 例如,我想進行注冊,因此我創建如下路線:

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);
});

用戶功能看起來像這樣(不是最終的):

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;
        });
    }
}

我嘗試做一些像MVC這樣的結構化應用程序。 問題是save方法是異步的,每次我讓新用戶registration.html都會獲取registration.html而無需等待結果。

基本上我需要在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);
    });
}

我發現,每當我使用某個模塊(例如db)並且使用回調時,對於包裹的任何函數,我通常都必須使用回調(除非我不在乎結果)。

這里:

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);
        });
    }
});

另外,您可能希望將對象方法放在原型中,而不是:

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

嘗試:

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

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Closures#Performance_considerations了解有關原因的信息。

有關組織Node.js應用程序的起點,請嘗試通讀此demo express.js應用程序上的源代碼。 點擊這里鏈接

這是一個相當受歡迎的倉庫,當我從頭開始構建Node.js應用程序時,我經常會發現自己在引用它。

鑒於它以MVC樣式完成並且使用貓鼬,因此它可能是對您的項目的很好參考。 路由被組織到一個文件中,該文件可以在config/routes.js找到。 您還應該查看app/models/中的app/models/ ,以另一種方式來組織用戶模型

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM