如何在Express中正确发送ID数组

4

我有一个id数组,如下所示:

var arr = [1, 23, 6];

我需要将此数组发送到服务器,解析它,并从mongoose数据库中删除ids。 我的后端使用nodejs express。 因此,我需要你的建议如何使用jQuery发送数组以及如何在服务器上解析它。

2个回答

9

基本上是对@udidu的好回答的评论,但我想使用markdown格式,所以我会把它发布成一个答案。下面是一些小的改进建议:

  • Omit everything but the path from the url "/deleteIds" on the javascript side so it will work no matter how it is served.

  • You can send the array as a JSON string without an object wrapper

    $.ajax({
        url: '/deleteIds',
        type: 'DELETE',
        data: JSON.stringify([1, 2, 3]),
        contentType: "application/json",
        processData: false,
        success: function(data){
            console.log(data);
        }
    });
    
  • In the server, the array will be available as just req.body

  • As per REST conventions, this should be using the HTTP DELETE method (I've changed the jquery. You will also need to change the express code to do app.del instead of app.post).


它被替换为{}了 :( - piggyback
1
使我的用例工作的最重要的设置:
  • 数据:JSON.stringify(...)
  • processData:false
  • contentType:“application/json”
- chitza
你所描述的“发送数组而不带对象封装器”的方式是错误的 - 你正在以字符串形式发送序列化版本的数组。你应该让jQuery来处理这个问题,或者解释为什么你要覆盖它的序列化过程。 - Dean Radcliffe
因为我阅读了jquery $.ajax文档,发现默认序列化方式不是JSON:“默认情况下,传递到数据选项的数据作为对象(技术上讲,任何不是字符串的东西)将被处理并转换为一个查询字符串,以适应默认的内容类型"application/x-www-form-urlencoded"。如果你想发送DOMDocument或其他未经处理的数据,请将此选项设置为false。” - Peter Lyons
@nick,请尝试使用JSON.parse(data)。 - Vladyslav Nikolaiev

4

好的,按照以下步骤操作即可:

首先,让我们创建一个Node服务器。我使用Express模块来定义HTTP服务器:

var fs = require('fs'),
    express = require('express'),
    app = express();


app.listen(8080);

app.use(express.bodyParser());

app.get('/', function(req, res){
    var html = fs.readFileSync('index.html');
    res.header("Content-Type", "text/html");
    res.send(html);
});

app.post('/deleteIds', function(req, res){
    console.log(req.body.arr[0]);
    res.json({ success: true });
});

服务器发出'/'请求返回一个HTML页面,该页面将创建一个jQuery Ajax请求。以下是HTML文件的内容:
<html>
<head>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
    <script type="text/javascript">

        $.ajax({
            url: 'http://localhost:8080/deleteIds',
            type: 'POST',
            data: {
                arr: [ 1, 2, 3]
            },
            success: function(data){
                console.log(data);
            }
        });

    </script>

</head>
<body>
</body>
</html>

正如你所看到的,html文件中的Ajax请求以一个数组作为数据发送POST请求,服务器中的/deleteIds express路径POST函数监听此请求并使用req.body.arr获取该数组,需要注意的是我使用了app.use(express.bodyParser());,如果没有这一行代码,我们将无法从POST请求中获取消息主体内容。
就是这样..我希望这有助于理解使用express进行Node + Ajax请求,从这一点上,您可以运行arr并对数据执行想要的操作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接