有没有办法可以 ajax 发布对象数组并在 Node.js 服务器上解析它?这是我的客户端代码:
var context = [];
obj1 = {
first_name: 'e',
last_name: 'e',
contact_email: 'e',
contact_phone_num: 'e',
contact_notes: 'e'
}
obj2 = {
first_name: 'a',
last_name: 'a',
contact_email: 'a',
contact_phone_num: 'a',
contact_notes: 'a'
}
var context = [];
context.push(obj1);
context.push(obj2)
$.ajax({
type: "POST",
url: '/api/addcontact',
data: context,
success: function(data, status) {
alert('company added!');
},
error: function(data, status, res) {
console.log('err: ' + res);
}
});
我的服务器端代码:
api.post('/api/addcompany', function(req, res) {
console.log('add company hit');
console.log(req.body); //returns {}
res.sendStatus(200);
});
现在,当我打印请求正文时,它会返回 {}
。
有人可以帮助我在服务器端正确访问对象数组吗?
提前致谢!
最佳答案
发生这种情况是因为您没有在ajax帖子中发送对象,而是发送数组。尝试将数组包装在 {}
中以表明它确实是一个对象,然后在服务器代码中引用该对象属性。
var context = []; // array
context.push(obj1);
context.push(obj2)
$.ajax({
type: "POST",
url: '/api/addcontact',
data: {context: context}, // requires an object here
success: function(data, status) {
alert('company added!');
},
error: function(data, status, res) {
console.log('err: ' + res);
}
});
然后在服务器端脚本中,您可以引用 body 对象的 context
属性。
关于javascript - 如何 AJAX POST 对象数组到 Node.js 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35807456/