从后端到前端传递消息
我正在学习节点和EJS,并且需要一些帮助。验证它后,我正在尝试从表单中获取数据并存储在数据库中。在验证期间,我无法将消息从后端传递到前端。我不确定我在做什么错。
后端代码:
let { agentname } = req.body;
let errors = [];
if (!agentname) {
errors.push({ message: 'Please enter all Mandatory Fields' });
}
if (errors.length > 0) {
res.render('addagent', { errors });
} else {
pool.query(
`SELECT * FROM agentinfo where agentname = $1`,
[agentname],
(err, results) => {
if (err) {
throw err;
}
console.log(results.rows);
if (results.rows.length >= 1) {
errors.push({ message: 'Agent is already added. Please check again' });
console.log(errors);
res.render('addagent', { errors });
}
}
);
}
前端:
<section class="addsec">
<div class="addagent">
<h3>Add Agent</h3>
<ul>
<% if(messages.error) { %>
<li> Test Message </li>
<li><%= messages.error %></li>
<% } %>
</ul>
</div>
</section>
我尝试在后端打印消息以进行验证,并且在后端工作正常,但是在前端看不到该消息。
请帮助理解和修复此错误
I'm learning Node and EJS and need some help with my program. I'm trying to get the data from Form and store in the database after validating it. During validation, I couldn't pass messages from backend to frontend. I'm not sure what I'm doing wrong.
Backend Code :
let { agentname } = req.body;
let errors = [];
if (!agentname) {
errors.push({ message: 'Please enter all Mandatory Fields' });
}
if (errors.length > 0) {
res.render('addagent', { errors });
} else {
pool.query(
`SELECT * FROM agentinfo where agentname = $1`,
[agentname],
(err, results) => {
if (err) {
throw err;
}
console.log(results.rows);
if (results.rows.length >= 1) {
errors.push({ message: 'Agent is already added. Please check again' });
console.log(errors);
res.render('addagent', { errors });
}
}
);
}
Front end:
<section class="addsec">
<div class="addagent">
<h3>Add Agent</h3>
<ul>
<% if(messages.error) { %>
<li> Test Message </li>
<li><%= messages.error %></li>
<% } %>
</ul>
</div>
</section>
I try to print the message in the backend for validation and it is working fine in the backend but that messages are not seen on the front end.
Please help to understand and fix this error
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在传递
错误
是对象数组,您应该能够使用以下方式访问消息:You are passing
errors
which is an array of object, you should be able to access the messages with:我通过纠正下面的前端代码来解决此问题。
I fixed this issue by correcting the front-end code like below.