对象数组未作为数组接收 node.js
Array of Objects not being received as an Array node.js
我正在传递一个包含 "wines" 数组的 POST。发送外观线上的对象。但是,当我在服务器端记录请求时,数组是键和值的集合。我错过了什么:
**** 我的测试请求代码 ****
request.post("http://localhost:3000/todos", {form: params}, function(err, response){
console.log(response.body);
})
**** 正在发送的选项 ****
var params = {
name: 'Test Do',
summary: 'This is the summary',
wines: ['56ad66897070ffc5387352dc', '56dg66898180ffd6487353ef']
}
**** 我的服务器端代码 --- 为简洁起见缩短 ***
exports.todoPost = function(req, res){
console.log(req.body);
var todo = new ToDo(req.body);
todo.save(function(err, todoX){
if(err){return res.send.err;}
console.log(req.body.store_config)
if(todo.wines){
**** 'console.log(req.body) ****
的输出
{ name: 'Test Do',
summary: 'This is the summary',
'wines[0]': '56ad66897070ffc5387352dc',
'wines[1]': '56dg66898180ffd6487353ef' }
我可以不在 POST 中发送数组吗?我在网上看到的所有内容以及我尝试过的所有内容都不起作用。它说我传递的东西正确。
从技术上讲,您确实使用 POST 发送了一个数组。它们只是处理方式不同。您可以做的一件事是将对象作为 JSON 字符串发送。
request.post("...", { form: JSON.stringify(params) }, function( ...
然后在服务器端,使用 JSON.parse
.
撤销字符串化
var params = JSON.parse(req.body);
我正在传递一个包含 "wines" 数组的 POST。发送外观线上的对象。但是,当我在服务器端记录请求时,数组是键和值的集合。我错过了什么:
**** 我的测试请求代码 ****
request.post("http://localhost:3000/todos", {form: params}, function(err, response){
console.log(response.body);
})
**** 正在发送的选项 ****
var params = {
name: 'Test Do',
summary: 'This is the summary',
wines: ['56ad66897070ffc5387352dc', '56dg66898180ffd6487353ef']
}
**** 我的服务器端代码 --- 为简洁起见缩短 ***
exports.todoPost = function(req, res){
console.log(req.body);
var todo = new ToDo(req.body);
todo.save(function(err, todoX){
if(err){return res.send.err;}
console.log(req.body.store_config)
if(todo.wines){
**** 'console.log(req.body) ****
的输出{ name: 'Test Do',
summary: 'This is the summary',
'wines[0]': '56ad66897070ffc5387352dc',
'wines[1]': '56dg66898180ffd6487353ef' }
我可以不在 POST 中发送数组吗?我在网上看到的所有内容以及我尝试过的所有内容都不起作用。它说我传递的东西正确。
从技术上讲,您确实使用 POST 发送了一个数组。它们只是处理方式不同。您可以做的一件事是将对象作为 JSON 字符串发送。
request.post("...", { form: JSON.stringify(params) }, function( ...
然后在服务器端,使用 JSON.parse
.
var params = JSON.parse(req.body);