简体   繁体   English

将消息从后端传递到前端

[英]Passing message from backend to frontend

I'm learning Node and EJS and need some help with my program.我正在学习 Node 和 EJS,我的程序需要一些帮助。 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请帮助理解并修复此错误

You are passing errors which is an array of object, you should be able to access the messages with:您传递的errors是一个对象数组,您应该能够通过以下方式访问消息:

<section class="addsec">
  <div class="addagent">
    <h3>Add Agent</h3>

    <ul>
      <% if (errors.length > 0) { %>
      <li>Test Message</li>
      <li><%= errors[0].message %></li>
      <% } %>
    </ul>
  </div>
</section>

I fixed this issue by correcting the front-end code like below.我通过更正如下所示的前端代码解决了这个问题。

 <ul>
    <% if(typeof errors != 'undefined') { %>
      <% errors.forEach(error =>{ %>
         <li><%= error.message %></li>
         <% }) %> 
      <% } %>
 </ul>

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM