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

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

Related

How would I get JSON information into, say, a variable, from a function using a callback in Javascript (nodejs)?

Alright, this could be really obvious, and I may not have worded the title correctly, I don't know.
I have this command that gets information on a starcraft profile, using this battlenet api. The function used to get a profiles information is
sc2.profile.profile({ id: profileId, region: profileRegion, name: profileName }, callback)
I want to be able to use the information from there for something else, and I want to pick and choose what I send and what I don't. Example:
console.log("Profile Name: " + response.displayName) /*response being the JSON, displayName being the only thing out of the JSON to be sent */
How would I go about doing that? Unfortunately I have to have a callback, and so far I haven't been able to use
var profileInfo = sc2.profile.profile({ id: profileId, region: profileRegion, name: profileName }, callback)
https://github.com/benweier/battlenet-api
callback Required. The callback function accepts two arguments error
and response.
error is only applicable when there's a connection issue to the API.
Otherwise null. body is the request response body parsed as JSON. If a
request is successful this value can still return API errors such as
'Character not found' or 'Account forbidden'. res is the response
information such as headers and statusCode
so your code would look like this
let someData;
sc2.profile.profile({ id: profileId, region: profileRegion, name: profileName },
(err, body, res) => {
// this function will be called when you receive response / error
someData = body.someData
}
);
Yo can use callback function and assign the result to a variable as following :
var profileInfo;
sc2.profile.profile({ id: profileId, region: profileRegion, name: profileName }, function(err,body,res){
profileInfo = res;
})

How to POST an XML with Angular http?

I'm having trouble using JavaScript to send xml. I've tried to emulate what many others have done, but I'm not getting success. I'm getting a XML Syntax Error: Please check the XML request to see if it can be parsed. with the code 80040B19.
Here's my code. I'm trying to use the USPS Address Validation API. On page 4 of this doc, there's more info.
const apiUrl = 'http://production.shippingapis.com/ShippingAPI.dll?API=Verify';
validate(address: Object): any {
const payload = this.xmlBuilder.buildObject({
AddressValidateRequest: {
$: { USERID: 'XXXXXXXXX' }, // api key hidden
Address: {
$: { ID: '0'},
FirmName: null,
Address1: address['address2'],
Address2: address['address1'], // NOT A TYPO, they swap it
City: address['city'],
State: 'NY',
Zip5: address['postal_code'],
Zip4: null
}
}
});
console.log(payload); // SEE BELOW
const headers = new Headers({ 'Content-Type': 'text/xml' });
const options = new RequestOptions({ headers: headers });
return this.http.post(this.apiUrl, { 'XML': payload }, options)
.map((res) => {
this.parseXMLStringToObject(res.text(), (err, result) => {
console.log(result);
});
});
}
Here's what my console.log on the payload reads. I've verified this to the letter, from the order of the xml tags, to what is required tag but optional value. I'm positive the payload is correct.
<AddressValidateRequest USERID="XXXXXXXXX">
<Address ID="0">
<FirmName/>
<Address1/>
<Address2>620 Eighth Avenue</Address2>
<City>New York</City>
<State>NY</State>
<Zip5>10018</Zip5>
<Zip4/>
</Address>
</AddressValidateRequest>
One thing that I can think of is I'm somehow not using the http correctly, and I'm sending a blank xml somehow.
On their docs, they have this listed:
https://servername/ShippingAPI.dll?API=Verify&XML=……..
I noticed I'm not doing a XML in the url, but I'm assuming that when I input the Content-Type: text/xml, that it get converted. I've also tried application/xml which give the same error.
From the documentation on USPS website it seems that the call isn't a POST with the XML as payload but a GET with XML (I suppose urlencoded) in the URL XML parameter.

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

How to access Angular Js data from nodejs

Hi in my angular js file, I have patient objects which contain name, number and appointment date. In my node js file, I use twilio to send a text a patient. What I want to know is how to get the number from the angular js file in order to use it in my node Js file so I can send the patient a text. Thanks.
here is the part of server.js where I send the text message
app.post('/testtwilio', function(req,res){
var cheerio = require('cheerio'),
$ = cheerio.load('file.html'),
fs = require('fs');
fs.readFile('./views/index.html', function (err, html) {
if (err) {
throw err;
} else {
$ = cheerio.load(html.toString());
console.log($scope.patients)//$('.reminder').attr('text'));
}
});
client.sendMessage({
to: '{{patient.number}}',
from: '+16173935460',
body: 'Text sent using NodeJS'
}, function(err, data){
if(err)
console.log(err);
});
})
Here is the patient object in the MainController.js
$scope.patients = [
{
name: 'John Smith',
date: "12/22/2016",
number: 1829191844
},
{
name: 'Matt',
date: "09/15/2016",
number: 1829198344
},
{
name: 'John',
date: "08/25/2016",
number: 1829198844
},
];
Pass the data from the front end to the backend? Have angular call a route on your backend with the data you need and access it with the req.params object.
Is your server.js a node.js controller?
In the angular controller you could import $http and just do a $http.post({myparams}, /myRoute, function(results){console.log(results)})
Like Mike says. The only way to really share files between the front end and the backend is if the files are JSON as that can be read by Angular and Node. However, I usually just use this for static configuration files.

NodeJS: Accessing object fields returns undefined even though fields exist

router.get('/:id', function(req, res, next){console.log(req.params.id)
request(
config.API_URL + "/v1/gallery/get?id=" + req.params.id,
function (err, response, body){
console.log('###BODY###',JSON.stringify(body));
console.log('###BODY###',JSON.stringify(body.data));
res.render('gallery', { user: req.session.user, gallery: body.data, title: 'Gallery', purchased: req.session.user.outlet ? (req.session.user.outlet.purchased || []) : [], config: config });
}
);
});
I'm trying to pass the request body's data field as the gallery for this template, but upon passing body.data, in the template it says my gallery argument is undefined. As you can see above, I then console logged the body and then its field. console.log(body) yields the following output:
###BODY### "{\"err\":null,\"data\": {\"_id\":\"5d955d7431d34f862a0dbd60\",\"owner
\":null,\"caption\":\"A suspected shooting at the Washington DC Navy Yard has sh
ut down parts of the city. This is the same location where a gunman killed 12 pe
ople in 2013. After an investigation search, authorities gave the \\\"all clear.
\\\"\",\"tags\":[\"dc\",\"navyyard\",\"shooting\",\"washington\"]...
I shortened the output, but as you can see, the data field is clearly there next to data.err. However, when I run console.log('###BODY###',JSON.stringify(body.data)), I am returned ###BODY### undefined. Can anyone explain this behavior please?
Replace this:
request(
config.API_URL + "/v1/gallery/get?id=" + req.params.id,
<callback>
);
With:
request({
url: config.API_URL + "/v1/gallery/get?id=" + req.params.id,
json: true
}, <callback>);
That will instruct request to automatically parse the response body as json (assuming you're using this request module, of course).

Categories

Resources