【问题标题】:Express JS: POST request to insert at DynamoDBExpress JS:在 DynamoDB 中插入的 POST 请求
【发布时间】:2018-07-08 12:28:23
【问题描述】:

我必须在 node.js 应用程序中使用 express 框架在 DynamoDB 表中插入以下数据

register.html

<input type = "text" placeholder="First Name" id = "txtFirstName"><br><br>
<input type = "text" placeholder="Last Name" id = "txtLastName"><br><br>        
<input type = "email" placeholder="Email" id = "txtEmail"><br><br>
<input type = "text" placeholder="Phone" id = "txtPhone"><br><br>
<input type = "text" placeholder="Zip Code" id = "txtZip"><br><br>

我知道我需要使用 this post 中提到的 express body-parser

但我不清楚如何使用所描述的body-parser 方法创建我需要插入到 DynamoDB 表中的 JSON。我可以使用 jQuery 来读取这些 html 项目并创建一个 JSON。例如,我需要创建一个如下所示的 JSON:

var paramsInsert = {
                TableName:tableName,
                Item:{
                        "email": email,
                        "info":{
                                "FirstName": fName,
                                "LastName": lName,
                                "Phone": phone,
                                "ZipCode": zip
                        }
                }
        };

这个paramsInsert 最终被传递给 DynamoDB 以插入到如下表中

insertAtTable(paramsInsert);

如何使用body-parser 方法创建paramsInsert

编辑: 在this link 之后,我写了下面的代码,但仍然没有得到输出

app.post('/register.html', function(req, res) {
  const { fname, lname, email, phone, zip } = req.body;
  console.log(fname)
}

【问题讨论】:

    标签: jquery node.js express amazon-dynamodb


    【解决方案1】:

    您似乎缺少输入元素上的 name 属性:

    <input type = "text" placeholder="First Name" id = "txtFirstName" name="firstName">
    <input type = "text" placeholder="Last Name" id = "txtLastName" name="lastName">      
    <input type = "email" placeholder="Email" id = "txtEmail" name="email">
    <input type = "text" placeholder="Phone" id = "txtPhone" name="phone">
    <input type = "text" placeholder="Zip Code" id = "txtZip" name="zip">
    

    指定name 属性后,您现在应该能够执行以下操作:

    app.post('/register.html', function(req, res) {
      const {
        firstName,
        lastName,
        email,
        phone,
        zip
      } = req.body
    
      const paramsInsert = {
        TableName: 'example',
        Item: {
          firstName,
          lastName,
          email,
          phone,
          zip
        }
      }
    }
    

    这可以通过使用ES2018's object spread来缩短:

    app.post('/register.html', function(req, res) {
      const paramsInsert = {
        TableName: 'example',
        Item: { ...req.body }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-11-04
      • 2017-12-08
      • 2014-01-27
      • 1970-01-01
      • 1970-01-01
      • 2019-06-26
      • 2015-06-26
      • 1970-01-01
      • 2023-01-10
      相关资源
      最近更新 更多