【发布时间】: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.account 和 post_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