2016-05-21 37 views
0

我在客戶端有一個表單,它通過我的Express應用程序中的AJAX將數據發送到服務器。我想在出現錯誤或消息發送成功時向用戶顯示一些響應。Express:在router.post和router.get之間共享邏輯

此代碼表示無法發送消息時的錯誤消息。在我的車把模板的具體DIV看起來是這樣的:

<div class="form-validation-error" style="{{formValidationError}}">ERROR: Message cannot be sent!</div> 

這是由CSS默認情況下關閉:

.form-validation-error { 
    display: none; 
} 

在我routes/contact.js我有一個router.post塊正在處理的消息發送:

router.post('/', (req, res, next) => { 
    if(req.body.firstname.length === 0 || !req.body.firstname.match(/\D+/igm)) { 
    var validateFirstname = false; 
    } else { 
    var validateFirstname = true; 
    }; 

    if(req.body.captcha.length === 0 || !req.body.captcha.match(/^kettő|ketto|two$/igm)) { 
    var validateCaptcha = false; 
    } else { 
    var validateCaptcha = true; 
    }; 

    if(validateFirstname === true && validateCaptcha === true) { 
    console.log('SUCCESS: Form validated! The Nodemailer script will be here!'); 
    } else { 
    console.log('ERROR: Form not validated!'); 
    const formValidationErrorTrue = 'display: block;'; // -> How can I achieve this!?? 
    res.send({formValidationError: 'display: block;'}); // -> Or this!?? 
    }; 
}); 

在這個塊之後,我有一個router.get模板渲染部分:

router.get('/', (req, res, next) => { 
    fsAsync((err, data) => { 
    if(err) { 
     res.render('404', { 
     title: 'Error 404' 
     }); 
    } 

    const contact = data[2].contact; 

    res.render('contact', { 
     title: 'Contact', 
     data: contact, 
     formValidationError: formValidationErrorTrue // -> How can I achieve this!?? 
    }); 
    }); 
}); 

我的問題是,我如何分享router.postrouter.get之間的變量?

回答

1

您可以創建一個方法並在get和post路由中調用該方法。我會將所有邏輯封裝在控制器中,而不是直接封裝在路由中。也許你也可以使用中間件(谷歌中間件)解決這個問題,但我通常會看到用於身份驗證或錯誤日誌記錄。

(對不起,我在我的手機上打字)

+0

謝謝你的想法。我想我會在'router.use'中寫一個Middleware函數。 – Lanti