简体   繁体   English

Node.js和Express:加载后更新router.get和res.render对象

[英]Node.js and Express: Updating router.get and res.render's object after load

I have this code, which is returns the following error on req.body.firstname.length inside router.use on the page load: 我有这段代码,它在页面加载时在req.body.firstname.length内的router.use上返回以下错误:

TypeError: Cannot read property 'length' of undefined

Because already checking the input forms value and the default value is undefined . 因为已经检查了输入表单的值,并且默认值为undefined I want to only check this code when it's getting req.xhr request from the AJAX form, not on the page load. 我只想在从AJAX表单获取req.xhr请求时检查此代码,而不是在页面加载时检查。 Is there a way to achieve this? 有没有办法做到这一点?

router.use((req, res, next) => {
  if(req.body.firstname.length === 0) {
    var validateFirstname = false;
  } else {
    var validateFirstname = true;
  };
  if(validateFirstname === true && validateCaptcha === true) {
    console.log('SUCCESS: Form validated!');
  } else {
    console.log('ERROR: Form not validated!');
  };
  next();
});

The reason why it's in a router.use , not in router.post , because I want to share this logic for router.get also, where my template rendering resides. 之所以将其router.userouter.post ,而不是在router.post ,是因为我也想为我的模板渲染所在的router.get共享此逻辑。

UPDATE: 更新:

Here is the relevant full code to get the idea what's going on: 以下是相关的完整代码,以了解发生了什么事情:

/////////////////////////////////////////////////////////////
// Nodemailer MIDDLEWARE
/////////////////////////////////////////////////////////////

router.post('/', (req, res, next) => {
  const firstname = req.body.firstname;
  req.firstname = firstname;

  if(req.firstname.length === 0) {
    var validateFirstname = false;
  } else {
    var validateFirstname = true;
  };

  if(validateFirstname === true) {
    console.log('SUCCESS: Form validated!');
    // send mail with defined transport object
    req.sending = true;
  } else {
    console.log('ERROR: Form not validated!');
    req.sending = false;
  };

  next();
});

router.use((req, res, next) => {
  // create reusable transporter object using the default SMTP transport
  req.transporter = nodemailer.createTransport({
    ...
  });
  // setup e-mail data with unicode symbols
  req.mailOptions = {
    ...
  };
  next();
});

/////////////////////////////////////////////////////////////
// Nodemailer
/////////////////////////////////////////////////////////////

router.post('/', (req, res, next) => {
  if(!req.xhr && req.sending === true) {
    // send mail with defined transport object
    req.transporter.sendMail(req.mailOptions, (err, info) => {
      if(err) {
        console.log('Error occurred');
        console.log(err.message);
      }
      console.log('Message sent successfully!');
      console.log('Server responded with "%s"', info.response);
      res.send('<div class="form-validation-success">SUCCESS: Message sent successfully!</div>');
    });
  } else {
    res.send('<div class="form-validation-error">ERROR: Message cannot be sent!</div>');
  };

/////////////////////////////////////////////////////////////
// INTERNAL API
// GET Contact page
/////////////////////////////////////////////////////////////

router.get('/', (req, res, next) => {
  res.render('contact', {
    title: 'Contact',
    formValidationError: req.displayBlock
  });
});

In my handebars template: 在我的把手模板中:

<div id="responseText"></div>

This code is now working but not updating the already rendered viewing template. 该代码现在可以正常工作,但不能更新已经渲染的查看模板。 I guess to only way to solve this to handle the server's response with AJAX, but how? 我想这是解决此问题的唯一方法,以使用AJAX处理服务器的响应,但是如何? This is the client-side AJAX code: 这是客户端AJAX代码:

'use strict';

(function() {
  document.getElementById('xhr').onclick = function() { makeRequest(); };

  function makeRequest() {
    var firstname = document.getElementById('firstname').value;
    var data = { firstname: firstname };
    // instance of a class that provides this functionality
    var xhr = new XMLHttpRequest();
    // decide what you want to do after you receive the server response to your request
    xhr.onreadystatechange = function() {
      try {
        // process the server response
        if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
          // everything is good, the response is received
          //alert(xhr.responseText);
          document.getElementById('responseText').innerHTML = xhr.responseText;
        } else {
          // still not ready
          alert('There was a problem with the request.');
        };
      } catch(e) {
        console.log('Caught Exception: ' + e.description);
      };
    };
    // make the request
    xhr.open('POST', '/en/contact', true);
    xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
    xhr.send(JSON.stringify(data));
  };
})();

It's always returning the There was a problem with the request error message, even when also returning xhr.responseText . 即使返回xhr.responseTextThere was a problem with the request错误消息仍然xhr.responseText

This router file resides at routes/contact.js and handling the requests at /:lang/contact . 该路由器文件位于routes/contact.js并在/:lang/contact处处理请求。 That's why you see '/' url in the file. 这就是为什么您在文件中看到'/' URL的原因。

can you please add some more information on it....as it is very difficult to figure out the problem with this information. 能否请您添加一些更多信息...。因为很难找出此信息的问题。

you are trying a post on uri /en/contact but receiving a request on / 您正在尝试关于uri / zh / contact的帖子,但收到有关/的请求

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Node.js和Express.js / Jade res.render返回res.render不是函数 - Node.js & Express.js/Jade res.render returns res.render is not a function Node.js和Express应用程序中res.render()和ejs.render()之间的区别是什么 - What's the difference between res.render() and ejs.render() in Node.js and Express app node.js-Express:将参数发送到res.render() - node.js - Express: Sending parameters to res.render() 在Node.js Express服务器中处理GET请求:res.render(file.ejs,data)不起作用,因为未定义数据 - Handling a GET request in Node.js Express server: res.render(file.ejs, data) not working because data is not defined Node.js / Express.js-如何覆盖/拦截res.render函数? - Node.js / Express.js - How to override/intercept res.render function? 如何在node.js(Express)中使用通过res.render传递的字典 - How to use dictionaries passed via res.render in node.js (Express) Node.js http.request使用单个res.render表达多个请求 - Node.js http.request Express multiple requests with single res.render node.js - express - res.render():将变量提供给JSON参数的正确格式? - node.js - express - res.render() : Correct format for feeding variables into the JSON parameter? 在 Node.Js Express 中,“res.render”是否结束了 http 请求? - In Node.Js Express, does “res.render” end the http request? 节点JS:res.render()之后res.download()错误 - Node JS : Error with res.download() after res.render()
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM