2012-09-30 83 views
2

最近有一個類似的問題,但仍然無法得到它。我必須在添加新用戶之前驗證註冊頁面。NodeJS - 如何打破功能?

app.post('/signup', function(req, res) { 
    //checking if first name is filled 
    if (req.body.first_name = "" || req.body.first_name = null || req.body.first_name = undefined) { 
     res.render('signup', { "title": "Ttitle", "menu": "signup", user: req.user, "error" : "empty_first_name" }); 
     break; 
    } 
    //checking if last name is filled 
    if (req.body.last_name = "" || req.body.last_name = null || req.body.last_name = undefined) { 
     res.render('signup', { "title": "Ttitle", "menu": "signup", user: req.user, "error" : "empty_last_name" }); 
     break; 
    } 
    //checking if email is filled 
    if (req.body.email = "" || req.body.email = null || req.body.email = undefined) { 
     res.render('signup', { "title": "Ttitle", "menu": "signup", user: req.user, "error" : "empty_email" }); 
     break; 
    } 
    //checking if passwords match 
    if (req.body.password != req.body.repassword) { 
     res.render('signup', { "title": "Ttitle", "menu": "signup", user: req.user, "error" : "pass_missmatch" }); 
     break; 
    } 
    ... 
    ... 
    ... 
    //and finally if everything seems to be OK... 
    addUser(req.body.email, req.body.password, req.body.first_name, req.body.last_name, req.body.country, function(status) { 
     res.render('signup', { "title": "Ttitle", "menu": "signup", user: req.user, "success" : 1 }); 
    }); 
}); 

Node.JS告訴我所有的休息都是非法的。但是,我應該如何以適當的方式打破我的功能?它不會返回任何東西。謝謝!

回答

12

A return語句用於暫停函數。

您可以提供一個可選的返回值,但在這種情況下,我相信它會被忽略,所以您應該可以將break;替換爲return;


側面說明,但你必須重複碼好一點,你必須在你的if條件下作業。你通常可以將重複因素排除在外。另外,如果您使用if/else if/else語句,則可以完全清除return

下面是一個例子。

function isEmpty(val) { 
    return val === "" || val == null; 
} 

function renderWithError(req, res, msg) { 
    res.render('signup', { "title": "Ttitle", "menu": "signup", user: req.user, "error" : msg }); 
} 

app.post('/signup', function(req, res) { 
    if (isEmpty(req.body.first_name)) { 
     renderWithError(req, res, "empty_first_name"); 
    } 
    else if (isEmpty(req.body.last_name)) { 
     renderWithError(req, res, "empty_last_name"); 
    } 
    else if (isEmpty(req.body.email)) { 
     renderWithError(req, res, "empty_email"); 
    } 
    else if (req.body.password != req.body.repassword) { 
     renderWithError(req, res, "pass_missmatch"); 
    } 
    ... 
    ... 
    ... 
    else { 
     addUser(req.body.email, req.body.password, req.body.first_name, req.body.last_name, req.body.country, function(status) { 
      res.render('signup', { "title": "Ttitle", "menu": "signup", user: req.user, "success" : 1 }); 
     }); 
    } 
}); 

+0

你的意思是像水木清華返回NULL? – f1nn

+0

@IlyaRusanen:只是'回來;'應該做的伎倆。沒有要求提供明確的返回值。 –

+0

它的工作,謝謝! – f1nn