【问题标题】:How do I handle form data from a form with multiple fields in node?如何处理节点中具有多个字段的表单中的表单数据?
【发布时间】:2020-10-28 09:46:28
【问题描述】:

我正在尝试建立一个页面,供人们回复婚礼网站的回复。客人输入他们的电子邮件地址,页面会找到该邀请中出现的所有客人,然后生成一个表格:

<%- include("./partials/header") %>
<h2>
    RSVP
</h2>




<div class="container">
    <div class=" row justify-content-center">
        <h5>Enter the email address that appears on your invitation.</h5>
    </div>
    <div class=" row justify-content-center">
        <div id="form-findGuest">
            <form action="/rsvp" method="GET">
                <input type="text" name="searchEmail" placeholder="email">
                <button type="submit">Submit</button>
            </form>
        </div>
    </div>
    
    <div class="row justify-content-center">
        <form action="/rsvp" method="POST">
            <table class="table">
                <% for(i=0;i<guests.length;i++){ %>
                    <tr>
                        <td><%= guests[i].name %></td>  
                        <% if(guests[i].isComing){ %>
                            <td>Attending</td>
                        <% } else { %>
                            <td>Not Attending</td>
                        <% } %>
                        <td>
                        <td>
                                <input type="checkbox">
                        </td>
                    </tr>
                <% }%>
            </table>
        </form>
    </div>
    <div class="row justify-content-center">
        <a href="/index" class="btn btn-secondary">Back</a>
    </div>
</div>



<%- include("./partials/footer") %>

问题是我不知道如何处理发布路线。基本上我想做这样的事情:

app.post("/rsvp", (req, res)=>{
//  parse the req.body and for each rsvp that got sent here, add it to some array
//  now use a for loop to iterate through that array and change the isComing value for each guest
    res.redirect("index")
})

但是当我不知道请求中有多少字段时,我无法弄清楚如何解析 req.body - 一些电子邮件地址可能只对应一位客人,但其他人可能对应,比如说五个。

【问题讨论】:

    标签: node.js forms express mongoose ejs


    【解决方案1】:

    如果尚未添加,则添加正文解析器,并使用

    对象.keys

    const express = require('express'),
      app = express(),
      bodyParser = require('body-parser');
    
    // support parsing of application/json type post data
    app.use(bodyParser.json());
    
    //support parsing of application/x-www-form-urlencoded post data
    app.use(bodyParser.urlencoded({ extended: true }));
        
    app.post("/rsvp", (req, res)=>{
    var keys = Object.keys(req.body);
    for(var i=0;i<keys.length;i++)
    {
    var guest=req.body[keys[i]];
    //  now use this to change the isComing value for each guest
    }
    
        res.redirect("index")
    })
    

    【讨论】:

    • 欢迎@DidymusHirsch 请给出“接受答案”,这样这个问题就会被关闭
    猜你喜欢
    • 1970-01-01
    • 2015-12-10
    • 1970-01-01
    • 2021-10-16
    • 2014-02-26
    • 2020-07-10
    • 1970-01-01
    • 2020-08-05
    • 1970-01-01
    相关资源
    最近更新 更多