[英]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.use
在router.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.responseText
, There 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.