【问题标题】:Posting nested object to nodejs server via ajax is returning undefined通过 ajax 将嵌套对象发布到 nodejs 服务器返回未定义
【发布时间】:2020-04-11 02:33:31
【问题描述】:

我已经尝试了几个小时来解决这个问题,但我似乎无法找到问题的原因。

在客户端 Javascript 上,我通过 ajax 将嵌套对象发布到我的后端 nodejs 服务器。 ajax 看起来像这样:

$.ajax({
  type: "POST",
  url: "/user/save",
  data: {
    "account": {
      "username": $signupForm.find("input[name='register_username']").val(),
      "email": $signupForm.find("input[name='register_email']").val(),
      "password": $signupForm.find("input[name='register_password']").val(),
      "plan": subscription
    },
    "stripe": stripeResponse
  },
  dataType: "json",
  beforeSend: function(){
    $.fn.showLoading();
  },
  success: function(data){

  }
});

然后我在我的 routes/index.js 中发现了这个

router.post('/user/save', function(req, res){
  var post_data = req.body;
  console.info(post_data);

  var account = post_data.account;
  var card = post_data.stripe;

  console.log(account);
  console.log(card);

  // Rest of code...

现在的问题是,由于某种原因,post_data.accountpost_data.stripe 都以未定义的形式返回。 post_data 本身确实会返回数据。

我也尝试使用 JSON.stringify 从 ajax 发送数据,但效果不佳。

我还需要 body-parser 并在 app.js 下使用

我看不出问题出在哪里。为什么我的数据未定义?

【问题讨论】:

  • console.info(post_data) 说什么?
  • @JohnWhite console.info(post_data) 返回我应该得到的数据:{ 'account[username]': "asd", 'account[email]': "asd", ... }

标签: ajax node.js body-parser


【解决方案1】:

在您的ajax() 设置中设置contentType: 'application/json; charset=UTF-8',否则使用application/x-www-form-urlencoded,这就是为什么您会看到按照您的方式格式化的数据。

由于请求发送的是 urlencoded 数据而不是 json(尽管有 dataType: "json"),另一个可能的解决方法是在服务器端的 bodyParser.urlencoded() 中间件选项中设置 extended: true。这将使解析器转换 urlencoded 请求数据,以便按照您的预期创建对象和数组。

【讨论】:

  • extended: true 成功了。非常感谢您的帮助以及有关扩展功能的信息。
【解决方案2】:

对我有用的是在客户端将数组转换为字符串,然后将其转换为 JSON 对象服务器端。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-18
    • 2010-12-15
    • 1970-01-01
    • 1970-01-01
    • 2017-11-27
    • 2023-03-17
    • 2021-01-28
    相关资源
    最近更新 更多