How to get POSTed (jquery) array data in Node.js (using express) - javascript

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"}]
I am posting using jquery:
$.post("save_names", {
'names[]': names
}, function(results) {
alert(results);
});
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);
});
This way i am getting the following from the console.log
body { 'names[]': [ '[object Object]', '[object Object]', '[object Object]' ] }
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]
Try converting data to JSON yourself:
$.post("save_names", {
'names[]': JSON.stringify(names)
}, function(results) {
alert(results);
});
Don't forget to correctly access your array: console.log("body ", req.body['names[]']);.

Yes, you req.body contains key names[], not names. So you can either grab from req.body['names[]'] or rewrite code to have name object:
$.post("save_names", {
names: names
}, function(results) {
alert(results);
});
And express code:
app.post('/alter_offer_sort', config.access_group, function(req, res) {
console.log("body ", req.body.names);
});
P.S. probably you grab [] names from a GET Query. It's not how POST works.
UPDATE:
I also don't notice, that there is just string of object, so initialize bodyParser.
First install body-parser:
npm install --save body-parser
Then modify code to this:
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())

Related

Not getting a specified data from get request in json server when i use something else rather than id

i want to get a specific user from json-server with his email here's my json file
{
"Person":[
{
"id":1,
"name":"Bahy",
"email":"bahy#gmail.com",
"password":"kkk",
"phone":"0221223213",
"gender":"M",
"dateOfBirth":"4/11/1999",
"type":"A",
"carddata":{"cardNumber":"anything","cardexpiary":"anything","cvv":"anything"}
},
}
and here's my function
getPerson(email: string): Observable<IPerson> {
return this.http.get<IPerson>(`${environment.ApiRootLink}/Person?email=${email}`);
}
and here's the usage of this function
user:IPerson;
getPerson(email?email:"").subscribe((data)=>{
this.user=data as IPerson;
console.log(this.user);
});
so this function intead of giving me the object it gives me this output
so does anyone know what kind of problem here bec when i try the same http on postman it works fine

String to array of JSON object

I try to send data to my NodeJS server using HTTP protocol (vue-resource). I want to send a array of JSON object like this : [{"name":"Charlotte","surname":"Chacha","birth":"2000-04-02"},{"name":"Michael","surname":"Mic","birth":"1999-01-30"}].
My front code :
window.onload = function () {
var gamme = new Vue({
el:'#gamme',
data: {
myListe: []
},
methods: {
sendListe: function() {
this.$http.get("/NewListe?liste="+this.myListe).then(response=> {
if (response.body) {
console.log(response.body);
}
});
}
}
})
}
And my back code :
server.app.get("/NewListe", function(req, res) {
try {
let liste= req.query.liste;
console.log(liste);
} catch (e) {
console.log(e);
}
})
When I try to display the variable liste in the server side console, I obtain this : [object Object] . liste is a string type that I can't use. I would like to have an array of JSON, like in front.
I tried to parse like this JSON.parse(operationsGamme) , but I have this error : SyntaxError: Unexpected token o in JSON at position 1
You should surely be using a POST method if you are sending JSON data to the server - a GET just isn't designed for that sort of usage.
Since you have passed a JSON in the url, it will be URLEncoded. So, in the backend before you do JSON.parse(liste), you should do decodeURI(liste). decodeURI() will return the JSON string which you can parse and use it in your code. I hope this will fix your problem.

How can I access my req.body data/json in Express?

I am new to node.js and I am trying to access json on my node.js server from a post request so I can send it to an API and feed it back to my front-end js file. I can see the json object, but I can't seem to access it(ex: req.body.name) after reading some documentation/stackoverflow posts.
Here is my post route from my server.js file, and packages:
var prettyjson = require('prettyjson');
var express = require('express');
var http = require('http');
var cors = require('cors');
var bodyParser = require('body-parser');
var app = express();
// create application/json parser
app.use(bodyParser.json());
// create application/x-www-form-urlencoded parser
app.use(bodyParser.urlencoded({
extended: true
}));
app.post('/', function(req, res) {
var test = req.body; //If I req.body.name here, it will return undefined
console.log(test);
});
Here is my front end map.js file post function and data:
var locations = [
{name:'Le Thai', coords:{lat:36.168743, lng:-115.139866}},
{name:'Atomic Liquors', coords:{lat:36.166782, lng:-115.13551}},
{name:'The Griffin', coords:{lat:36.168785, lng:-115.140329}},
{name:'Pizza Rock', coords:{lat:36.17182, lng:-115.142304}},
{name:'Mob Museum', coords:{lat:36.172815,lng:-115.141242}},
{name:'Joe Vicari’s Andiamo Italian Steakhouse', coords:{lat:36.169437, lng:-115.142903}},
{name:'eat', coords:{lat:36.166535, lng:-115.139067}},
{name:'Hugo’s Cellar', coords:{lat:36.169915, lng:-115.143861}},
{name:'Therapy', coords:{lat:36.169041, lng:-115.139829}},
{name:'Vegenation', coords:{lat:36.167401, lng:-115.139453}}
];
//convert array to JSON
var jsonStr = JSON.stringify(locations);
$.post('http://localhost:3000/', jsonStr, function(data){
//empty for now
},'json');
End goal: I want to be able to access my data like req.body.name. I tried using typeof on req.body, and it returns an object, however I can't seem to access this object. And I tried using JSON.parse, but realized req.body is already an object. I would like to serve this data to the Yelp API eventually.
Current output(per request) from console.log(req.body):
{ '{"name":"Le Thai","coords":{"lat":36.168743,"lng":-115.139866}},
{"name":"Atomic Liquors","coords":{"lat":36.166782,"lng":-115.13551}},
{"name":"The Griffin","coords":{"lat":36.168785,"lng":-115.140329}},
{"name":"Pizza Rock","coords":{"lat":36.17182,"lng":-115.142304}},
{"name":"Mob Museum","coords":{"lat":36.172815,"lng":-115.141242}},
{"name":"Joe Vicari’s Andiamo Italian Steakhouse","coords":
{"lat":36.169437,"lng":-115.142903}},{"name":"eat","coords":
{"lat":36.166535,"lng":-115.139067}},{"name":"Hugo’s Cellar","coords":
{"lat":36.169915,"lng":-115.143861}},{"name":"Therapy","coords":
{"lat":36.169041,"lng":-115.139829}},{"name":"Vegenation","coords":
{"lat":36.167401,"lng":-115.139453}}': '' }
You're using an array, so it will not be:
req.body.name
but e.g.
req.body[0].name
You probably want to iterate over the array that you get with .forEach or a for loop etc.
The problem is you're not telling the server you're sending it JSON, so it's not getting parsed. Also, as rsp pointed out, to access the first name, you'd want req.body[0].name, not req.body.name.
The dataType parameter on $.post isn't to tell the server what you're sending it, it's to tell jQuery what you're expecting back from the server. To tell the server what you're sending it, use $.ajax and the contentType option:
$.ajax({
url: 'http://localhost:3000/',
type: "POST",
contentType: "application/json", // <====
data: jsonStr,
success: function(data){
//empty for now
}
});
Now, the body-parser module sees the content type on the request, and parses it for you. So for instance, if I change your server file to do this:
app.post('/', function(req, res) {
req.body.forEach(function(entry, index) {
console.log(index, entry.name)
});
});
...then with the change above to the client code, I get this on the server console:
0 'Le Thai'
1 'Atomic Liquors'
2 'The Griffin'
3 'Pizza Rock'
4 'Mob Museum'
5 'Joe Vicari’s Andiamo Italian Steakhouse'
6 'eat'
7 'Hugo’s Cellar'
8 'Therapy'
9 'Vegenation'
For those getting an empty object in req.body
I had forgotten to set headers: {"Content-Type": "application/json"} in the request. Changing it solved the problem

Issue passing data to child routes in Node.js

Im new to Node.js and keep getting the Error: Route.get() requires callback functions but got a [object Undefined] error
and Ive checked out the following question and either dont understand or im still doing something wrong
Express routes: .get() requires callback functions but got a [object Object]
.get() requires callback functions but got a [object Undefined]
Error: Route.get() requires callback functions but got a [object Undefined]
Node Route.get() requires callback function but got a [object undefined]
my file structure is
server.js
routes/api/geolocations.js
routes/api/geolocations/regions.js
routes/api/geolocations/destination.js
ROOT: server.js
var geolocation = require('./routes/api/geolocation')(app);
app.get('/geolocation/', geolocation.delegate);
then I pass my data to routes/api/geolocations.js by using
geolocation.delegate(unparsedData);
from there I parse the data and send it down it's appropriate child routes.
PARENT: geolocations.js in my routes/api/geolocations.js
var destination = require('./geolocations/destination');
var region = require('./geolocations/region');
module.exports = function(app) {
return {
app.get('./geolocation/region', region.delegate);
app.get('./geolocation/destination', destination.delegate);
delegate: function(unparsedData, req, res) {
var data =[setup package for child states using unparsedData]
//HERE Id like to pass the new `data` to region or destination using the following
region.delegate(data);
//OR
destination.delegate(data);
CHILDREN: region.js / destination.js in routes/api/geolocations/regions.js or routes/api/geolocations/destination.js
module.exports = function(app) {
return {
delegate: function(data, req, res) {
...do stuff
}
}
}
UPDATE: I guess I dont know where to set up my routes, in server.js or if i can in geoloaction.js, does it matter, do need to do something like this in server.js?
var regions = require('./routes/api/geolocation/regions')([pass stuff here]);
geolocation.get('./routes/api/geolocation/regions', regions.delegate);
You should use express.js easy setup and run.
Simply download IntelliJ IDEA, find free version, then install. Then run the application and goto File->Setting->Plugin and search for NodeJS then install. Followed to this you need to Enable it. To do this goto File->Setting->Language & Frameworks->open arrow-> JavaScriptopen arrow->Libraries->Enable Node.js Core.
File Structure
routes/api/geolocations.js
routes/api/geolocations/regions.js
routes/api/geolocations/destination.js
You can have a look at the below code that might help you get started.
//------------------------------------------------------------------------
var express = require('express');
var router = express.Router();
var regions = require('../api/geolocations/regions');
var destination = require('../api/geolocations/destination');
//------------------------------------------------------------------------
//------------------------------------------------------------------------
/* geolocation.js */
router.get('/', function(req, res, next) {
var region_ext = regions.to_export;
var destin_ext = destination.to_export;
res.render('index', {
title: 'Geolocation',
region: region_ext,
destination:destin_ext
});
});
module.exports = router;
//------------------------------------------------------------------------
//------------------------------------------------------------------------
/* region.js */
var to_export = function () {
return 'this is from regions';
}
module.exports.to_export = to_export();
//------------------------------------------------------------------------
//------------------------------------------------------------------------
/* destination.js */
var to_export = function () {
return 'this is from destination';
}
module.exports.to_export = to_export();
//------------------------------------------------------------------------
//------------------------------------------------------------------------
//In app.js, just change
var routes = require('./routes/api/geolocations');
//------------------------------------------------------------------------
jfriend00 is right, You got a little mess there. Maybe you should consider make use of next(), since if you use it the other middlewares will have a chance of manipulating the request.

Array of Objects not being received as an Array node.js

I am passing a POST that includes an array of "wines". The object on the send looks line. However when I log the request on the server side, the array is a collection of keys and values. What am I missing:
**** MY TEST REQUESTING CODE ****
request.post("http://localhost:3000/todos", {form: params}, function(err, response){
console.log(response.body);
})
**** THE OPTION AS IT IS BEING SENT ****
var params = {
name: 'Test Do',
summary: 'This is the summary',
wines: ['56ad66897070ffc5387352dc', '56dg66898180ffd6487353ef']
}
**** MY SERVER SIDE CODE --- SHORTEN FOR BREVITY ***
exports.todoPost = function(req, res){
console.log(req.body);
var todo = new ToDo(req.body);
todo.save(function(err, todoX){
if(err){return res.send.err;}
console.log(req.body.store_config)
if(todo.wines){
**** THE OUTPUT OF 'console.log(req.body) ****
{ name: 'Test Do',
summary: 'This is the summary',
'wines[0]': '56ad66897070ffc5387352dc',
'wines[1]': '56dg66898180ffd6487353ef' }
Can I not send an array in a POST? Everything I see online and everything I've tried isn't working. It says I'm passing stuff correctly.
Technically you did send an array using POST. They're just handled differently. One thing you could do instead is send the object as a JSON string.
request.post("...", { form: JSON.stringify(params) }, function( ...
Then on the server-side, just undo the stringifying by using JSON.parse.
var params = JSON.parse(req.body);

Categories

Resources