通过ajax发布嵌套对象到nodejs服务器返回undefined
我一直在试图找出几个小时,但我似乎无法find问题的原因。
在客户端JavaScript我张贴嵌套对象通过ajax到我的后端nodejs服务器。 阿贾克斯看起来像这样:
$.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.account
和post_data.stripe
被返回为undefined。 post_data本身确实返回数据。
我也尝试使用JSON.stringify
从ajax发送数据,但这并没有工作。
我也有要求身体分析器和app.js下使用
我看不到我的问题在哪里。 为什么我的数据未定义?
设置contentType: 'application/json; charset=UTF-8'
在你的ajax()
设置中使用contentType: 'application/json; charset=UTF-8'
,否则使用application/x-www-form-urlencoded
,这就是为什么你看到格式化数据的原因。
另一个可能的解决方法,因为请求是发送urlencoded数据而不是json(尽pipedataType: "json"
),是在服务器端的bodyParser.urlencoded()
中间件选项中设置extended: true
。 这将使parsing器转换urlencoded请求数据,以便按照您的预期创build对象和数组。