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.post
和router.get
之間的變量?
謝謝你的想法。我想我會在'router.use'中寫一個Middleware函數。 – Lanti