How to correctly send an array of identifiers to express

I have an array of identifiers like the following:

var arr = [1, 23, 6]; 

I need to send this array to the server, parse it and remove the identifiers from mongoose db. For my backend, I am using nodejs express. So I need to tell how to send the array using jQuery and how to parse it on the server.

+1
source share
2 answers

Ok, follow these instructions and you are good:

First of all, let's create our node server, I use 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 }); }); 

Server request // returns an HTML page that will create a jQuery Ajax request. Here is the contents of the HTML file:

 <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 data, the POST function /deleteIds express in the server listens for this and accepts the array using req.body.arr , note that I use app.use(express.bodyParser()); , without this line, we cannot get the body contents from the POST request.

That's all. Hope this helps to understand node + Ajax requests using express, from now on you can run on arr and do what you want with the data.

+4
source

Basically a comment on @udidu is a good answer, but I want markdown formatting, so I will post it as an answer. Here are some minor suggestions for improvement:

  • Omit everything except the path from url / deleteIds on the javascript side so that it works no matter how it is served.

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

     $.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 only be available as req.body

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

+5
source

Source: https://habr.com/ru/post/1242271/


All Articles