Express:在router.post和router.get之间共享逻辑

时间:2016-05-21 18:17:35

标签: javascript ajax node.js express

我在客户端有一个表单,它通过我的Express应用程序中的AJAX向服务器发送数据。我想在出现错误或成功发送消息时向用户显示一些回复。

此代码表示无法发送邮件时的错误消息。我的车把模板中的特定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 个答案:

答案 0 :(得分:1)

您可以创建一个方法,并在get和post路由中调用该方法。我会将所有逻辑封装在控制器中,而不是直接封装在您的路径中。也许您也可以使用中间件(谷歌快递中间件)解决这个问题,但我通常会看到用于身份验证或错误记录。

(对不起,简短的回答。我在手机上打字)