【问题标题】:Array of Objects not being received as an Array node.js对象数组未作为数组 node.js 接收
【发布时间】:2016-05-10 13:49:39
【问题描述】:

我正在传递一个包含“葡萄酒”数组的 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 中发送数组吗?我在网上看到的一切以及我尝试过的一切都不起作用。它说我正确地传递了东西。

【问题讨论】:

    标签: javascript arrays node.js request javascript-objects


    【解决方案1】:

    从技术上讲,您确实使用 POST 发送了一个数组。他们只是处理方式不同。您可以做的一件事是将对象作为 JSON 字符串发送。

    request.post("...", { form: JSON.stringify(params) }, function( ...
    

    然后在服务器端,只需使用JSON.parse 撤消字符串化。

    var params = JSON.parse(req.body);
    

    【讨论】:

    • 有没有办法处理当前收到的数组?当我控制台日志 (todos.wines) 或 (todos.wines[0]) 都返回为空。
    • @KJCarlson 有。如果您使用的是 Express,您可以安装 body-parser 模块,它应该会自动处理将其转换为数组。否则,您需要过滤掉键名或自己进行转换。 (注意:试试todos['wines[0]'] ,你会得到你想要的,但它不会在数组中。)
    • 谢谢,@Mike-C。我意识到在我已经将它投射到模型之后我试图调用它,而不是从 req.body['wines[0]'] 中提取变量
    猜你喜欢
    • 2012-07-29
    • 2021-01-06
    • 1970-01-01
    • 2019-11-19
    • 1970-01-01
    • 1970-01-01
    • 2017-07-25
    • 2023-03-12
    • 1970-01-01
    相关资源
    最近更新 更多