【问题标题】:Express.js access fields of serialized Form DataExpress.js 访问序列化表单数据的字段
【发布时间】:2016-06-29 12:13:11
【问题描述】:

我在快速路由器中访问序列化表单数据的特定字段时遇到了困难。

这是我的 ajax 请求:

var formData = $("#add-fut-account-form").find("select, textarea, input").serialize();
$.ajax({
  url: "/accounts/insert",
  type: "POST",
  data: {formData},
  success: function (response) {
    $("#addFutAccountResponse").append(response);
  },
  error: function (xhr) {
    alert("Error while trying to insert a new account!");
  }
})

这是我的路由器:

router.post('/insert', function(req, res)
{
    var formData = req.body.formData;
    console.log(formData);
});

我的 console.log() 输出:

email=kentor%40gmail.com&password=dsadsa&secret=123&platform=P&account-type=x&proxy=&rpm=8&threshold=3.5&optional-comment=&is-active=on

我的问题:

我应该如何序列化/发送/接收我的 formData,以便我可以轻松地访问表单中的特定字段(例如电子邮件、密码)。我尝试使用不起作用的req.body.formData.email(结果:未定义)。我知道两种可能的方法来解决这个问题,但它们似乎是一种迂回的方式。因此,我想知道使用 express 处理 formdata 的最佳做法是什么。

编辑:我已经在我的 app.js 中使用 bodyParse:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

【问题讨论】:

    标签: javascript node.js express


    【解决方案1】:

    尝试按如下方式制作 ajax:

    var formData = $("#add-fut-account-form").find("select, textarea, input").serialize();
    
    $.ajax({
      url: "/accounts/insert",
      type: "POST",
      data: formData,
      success: function (response) {
        $("#addFutAccountResponse").append(response);
      },
      error: function (xhr) {
        alert("Error while trying to insert a new account!");
      }
    })
    

    删除数据上的花括号

    【讨论】:

    • 你说得对,这就是我简化实际场景时发生的情况。我如何将数据与表单数据一起传递?我使用了 data: {"formData": formData, "additionalInfo": 123} 然后我想访问 req.body.formData.email ,但它不起作用。
    • 你可以使用serializeArray,它会返回一个对象数组,所以你可以简单地将一个项目推到那里,但是它可能会改变你访问这些项目的方式。您可以使用简单的 for 循环将 aray 转换为实际的 js 对象。当然你可以简单地在你的表单中添加一个隐藏的输入:)
    猜你喜欢
    • 2014-04-14
    • 1970-01-01
    • 2011-03-01
    • 1970-01-01
    • 2011-02-14
    • 2020-08-06
    • 1970-01-01
    • 2015-10-09
    • 2016-04-14
    相关资源
    最近更新 更多