如何在Node.js中获取POSTed(jquery)数组数据(使用express) [英] How to get POSTed (jquery) array data in Node.js (using express)

查看:67
本文介绍了如何在Node.js中获取POSTed(jquery)数组数据(使用express)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数组发布到我的服务器上。但是我很难做到这一点。

I am trying to post an array to my server. But I have difficulties in doing it properly.

我想发布的数组是一个动态结构化的对象数组,因此我不知道它的长度。

The array I am trying to post, is an array of objects which is dynamically structured, thus I don't know it's length.

更准确地说,我的数组就是这种形式。

To be more precise, my array is of the form.

var names =[{id:1, name:"nick"},{id:2,name:"bob"},{id:3,name:"john"}.....{id:n, name:"whatever"}]

我使用jquery发布:

I am posting using jquery:

$.post("save_names", {
        'names[]': names
    }, function(results) {
        alert(results);
    }); 

我的节点代码如下:(我使用stormpath-express)

My node code, is the following: (I use stormpath-express)

app.post('/save_names', config.access_group, function(req, res) {
    console.log("body ", req.body);
});

这样我从console.log获得以下内容

This way i am getting the following from the console.log

body  { 'names[]': [ '[object Object]', '[object Object]', '[object Object]' ] }

当我尝试打印数组时: console.log(body,req.body .names);
我得到正文未定义

When i try to print the array : console.log("body ", req.body.names); I get body undefined

有人可以解释一下为什么会这样?如何解决我的错误,为什么我不能只发布名字:名字和简单的工作?

Can somebody explain why this is happening? How to solve my error, and why can't I just post names:names and simply work?

推荐答案

你正在发送你的数据不正确。您可以在开发工具中检查请求。你会看到这样的东西:

You're sending your data incorrectly. You can examine request in Development tools. You'll see something like this:

Form Data
    names[]:[object Object]
    names[]:[object Object]
    names[]:[object Object]
    names[]:[object Object]

尝试自己将数据转换为JSON:

Try converting data to JSON yourself:

$.post("save_names", {
        'names[]': JSON.stringify(names)
    }, function(results) {
        alert(results);
    });

不要忘记正确访问你的数组: console.log( body,req.body ['names []']);

Don't forget to correctly access your array: console.log("body ", req.body['names[]']);.

这篇关于如何在Node.js中获取POSTed(jquery)数组数据(使用express)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆