How to send array of ids correctly in express

I have array of ids like the follows:

var arr = [1, 23, 6];

I need to send this array to a server, parse it, and remove the ids from a mongoose db. For my backend I'm using nodejs express. So I need your advise how should I send the array by using jQuery and how should I parse it on a server.

Ok, follow this instructions and you are good:

first of all, lets create our node server, I'm using the Express module to define the HTTP server:

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 });
});

The server '/' request returns an HTML page that will create an jQuery Ajax request, Here is the HTML file content:

<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>

As you can see, the Ajax request in the html file sent as a POST request with an array as the data, The /deleteIds express path POST function in the server listens to that and takes the array using req.body.arr, note that I'm using app.use(express.bodyParser());, without this line we will not be able to get the body content from the POST request.

This is it.. I hope this is helping understand Node + Ajax requests using express, from this point you can run on the arr and do what you want with the data.

Basically a comment on @udidu's good answer, but I want markdown formatting so I'll post it as an answer. Here's some minor improvement suggestions:

  • 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 plain array 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.