{ 'id': req.body.groups.id, 'title': req.body.groups.title, 'teamMemberIds': [ req.body.groups.teamMemberIds] }]
You cannot access fields of array's elements like this: req.body.groups.id, req.body.groups.title and req.body.groups.teamMemberIDs. In order to get the fields in the nested array you would have to do something like this req.body.groups[index].id.
But doing all of that is not necessary, since your req.body and mongoose schema are the same you can simply pass in the whole req.body.groups into groups like shown below.
app.post(`/api/add`, async (req, res) => {
collection.create( { 'id': req.body.id,
'name': req.body.name,
'date': req.body.date,
'groups': req.body.groups //change this line of code.
},
(err, result ) => {
if (err) {
console.log('error', err)
} else {
console.log('updated', result);
res.status(200).send(result);
}
})
});
Or even better you could just add the entire req.body to collection.create()
app.post(`/api/add`, async (req, res) => {
collection.create(req.body,
(err, result ) => {
if (err) {
console.log('error', err)
} else {
console.log('updated', result);
res.status(200).send(result);
}
})
});
In case when your req.body and mongoose schema have different formats, then for the array parts you can use the array method map to change the array format prior to document creation.
Parsing arrays in req.body in node js express
How to send array as req.body on node js source?
How Can I Pass Array in http.request node?
node.js use request make http calls to transfer the correct array format array - Stack Overflow
You can use body-parser in your app.js like this:
app.use(bodyParser.urlencoded({
extended: true
}));
Let's say you are receiving array in the post request body with the key: users you will parse it like this:
req.body.users
(It contains the users array)
Do you want to get the value from the key ?
for (var key in req.body) {
if (req.body.hasOwnProperty(key)) {
let value = req.body[key];
console.log( `value for
{value}` )
}
}
The /transfer endpoint receives obj as 'array[0]': '3', 'array[1]': '4', 'array[2]': '5' because the Content-Type of the HTTP request is application/x-www-form-urlencoded -- in the request.post() option, form property is used.
In order to send JSON object to /transfer, the Content-Type should be application/json. In module request, it can be implemented as below:
var request = require('request');
var obj={
tag: 'false',
array: [ '3', '4', '5']
};
// requestb.in URL is used here for example, but it can be replaced.
request({
url: 'https://requestb.in/srp1bmsr',
method: 'post',
body: obj,
json: true
}, function(err, response, body) {
if(err){
// deal with error.
}else{
// deal with success response.
}
});
According to module request's document, body and json in the code means:
body - entity body for PATCH, POST and PUT requests. Must be a Buffer, String or ReadStream. If json is true, then body must be a JSON-serializable object.
json - sets body to JSON representation of value and adds Content-type: application/json header. Additionally, parses the response body as JSON.
You can set headers using the headers property.
request.post({
url:/localhost/transfer,
body: obj,
json: true
},function(err,httpResponse,body){
if(err){
res.json({error:false});
}else{
res.json({error:true});
}
});
You can also set json: true, then it will add the header automatically and also parse the response body as JSON.
Because the body here is and array, to get the Id property, you'd need to use body[0].Id.
But if there's ever a chance that there's more than one object in the array, to get each of the Ids, you'd have to loop over the body:
for(let i = 0, l = body.length; i < l; i++) {
console.log(body[i].Id); // gets the Id property of this specific object in body
}
it seem to be an array so you should use
body[0].Id
Trying to access and Array from an multipart-form-data is a little bit tricky, but you can inspect the req.body and figure it out, the best solution for me in this case will be, since I think you're using jQuery or for that matter, native XMLHttpRequest or Fetch, you can send the form content as application/json, quick jQuery example:
const data = {
fields: [1, 2, 3]
}
jQuery.ajax({
data: JSON.stringify(data),
contentType: 'application/json'
})
Then in your express route you can access in a very comfortable manner, like this:
app.post('/route', function(req, res) {
const fieldsArray = req.body.field;
})
Hope this will be helpful, cheers.
You can simply create a json object of your data. The json object may contain nested objects, arrays, etc. Then JSON.stringify the data and send it over to node.
It will be good practice to set content-type: application/json
At node level, you can simply do var obj = JSON.parse(req.body.data) and it will return you javascript object that you encoded.
You can look here for reference: Javascript : Send JSON Object with Ajax?
In Rest GET methods uses the URL as the method to transfer information if you want to use the property data in your AJAX call to send more information you need to change the method to a POST method.
So in the server you change your declaration to:
app.post( instead of app.get(
If you're using ExpressJS server-side, req.body only contains data parsed from the request's body.
With GET requests, data is instead sent in the query-string, since they aren't expected to have bodies.
GET /controller/method?ids[]=482944&ids[]=...
And, the query-string is parsed and assigned to req.query instead.
console.log('my ids = ' + JSON.stringify(req.query.ids));
// ["482944","335392","482593",...]
You can send your array with the Postman by following the steps below:

your json must be like this:
{
"data" : [
{ "name": "ABC",
"amount": 1500
},
{ "name": "NNS",
"amount": 5800
},
{ "name": "GED",
"amount": 3500
},
{ "name": "PQ",
"amount": 5500
}
]
}
and you can retrieve this POST query in node (express) like this:
var bodyParser = require('body-parser')
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.post('/people', function(req, res, next) {
//show received data
console.log(req.body.data);
});
send in data parameters
key => value
data[] => {"name": "ABC", "amount": "1500"}
data[] => {"name": "ABC", "amount": "1500"}
data[] => {"name": "ABC", "amount": "1500"}
but i think this will convert the value to string ["{name:value}",...]
Ok, from your question I understand that you want to manipulate the POST Body like a json array then use qs library by making extended true
app.use(bodyParser.urlencoded({ extended: true }));
You can send an string instead of array and keep the extended option in false.
From your front js:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
$.ajax("/send", {
data: { "strArr": fruits.join() },
type: "POST",
async: true,
......
From your server js:
router.post('/send', function(req, res) {
var fruits = req.body.strArr.split(",");
console.log(fruits); // This is an array
});
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 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.bodyAs per REST conventions, this should be using the HTTP
DELETEmethod (I've changed the jquery. You will also need to change the express code to doapp.delinstead ofapp.post).
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.
I have an array and I want to receive it through a get request, but if I try to pass it
TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received an instance of Array
and if I turn the array into a string, then it will become a string (logical) and it will not work back into an array
One option is using a JSON format.
http://server/url?array=["foo","bar"]
Server side
var arr = JSON.parse(req.query.array);
Or your own format
http://server/url?array=foo,bar
Server side
var arr = req.query.array.split(',');
Express exposes the query parameter as an array when it is repeated more than once in the request URL:
app.get('/', function(req, res, next) {
console.log(req.query.a)
res.send(200)
}
GET /?a=x&a=y&a=z:
// query.a is ['x', 'y', 'z']
Same applies for req.body in other methods.