I cant read params value from req.params in restify (node JS) - javascript

I am trying to read the parameters value from req.params but in a different way (I am trying to make an API in RESTIFY).
First I read the keys that are available in req.params, like;
var requestData = Object.keys(request.params);
And than I loop through each key and try to fetch its value. below is the code;
for(i = 1; i < requestData.length; i++) {
keyValue = requestData[i];
console.log(request.params.keyValue);
}
But the output shows me UNDEFINED.
Reason: I am trying to read the parameters this way because, then, I do not need to know the name of each parameter.
Below is the complete code:
var restify = require('restify');
var assert = require('assert');
var server = restify.createServer();
var client = restify.createStringClient({
url: 'http://example.com'
});
function onRequest(request, response, next)
{
console.log(request.params);
var requestData = Object.keys(request.params);
var customJsonString = '';
var keyValue = '';
for(i = 1; i < requestData.length; i++) {
keyValue = requestData[i];
console.log(request.params.keyValue);
customJsonString += "" + requestData[i] + " : " + requestData[i] + ", ";
}
console.log(customJsonString);
}
function start()
{
server.use(restify.fullResponse()).use(restify.bodyParser());
server.get(/^\/(.*)/, onRequest);
server.post(/^\/(.*)/, onRequest);
server.listen(8888);
console.log("Server has started.");
}
exports.start = start;
I will really appreciate any help regarding this issue.

Try this instead:
console.log(request.params[keyValue]);
request.params.keyValue means Give me the value of the property keyValue, whereas the code above means Give me the value of the property whose name is stored in the variable keyValue.
Also, are you sure you want to start with i = 1? Javascript-arrays are 0-based, so I think you want i = 0 instead.

It could help if you can give us the URL you are testing right now as well as the console output your get.
However, please note that arrays in Javascript have 0 based index and your loop should look like this:
for(var i = 0; i < requestData.length; i++) {
}
To loop through the properties of an object, you should probably use for..in anyway:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
I don't know if that will solve your problem but it's a start.

Related

nodejs express sent object not synchronized with front end

I am trying to send an object from nodejs server to the front end but one property is keep getting deleted on the way
server
router.post('/cart/retrieve', (req, res) => {
let cart = req.session.cart;
let prodId = Object.keys(cart);
Product.find({_id: {$in: prodId}}, (err, result) => {
if (err) throw err;
let resultToSend = [];
for (let i = 0; i < result.length; i++) {
let curResult = result[i];
curResult['cartQuantity'] = parseInt(cart[curResult._id]);
result[i] = curResult;
}
resultToSend = result;
console.log(resultToSend[0]['cartQuantity'])
res.json({cart: resultToSend})
});
});
frontend
$("#top-cart-trigger").click(function(e){
$.post('/api/shop/cart/retrieve',{
}, function (returnResult) {
console.log(returnResult['cart'][0]['cartQuantity'])
let products = returnResult['cart'];
console.log(returnResult)
for(let i = 0; i < products.length; i ++){
let curProduct = products[i];
console.log(curProduct['cartQuantity'])
}
});
});
so practically the json variable sent from server and the returnResult received from the front end are same variables. However, my console.log(resultToSend[0]['cartQuantity']) returns 3 (which is correct) but console.log(curProduct['cartQuantity']) is undefined for all elements. What am I doing wrong?
I think the problem might comes from mutable variable result in your server.
However it seems like the variable returnResult['cart'] is JSON and you are expecting array. You could use 'for in' instead. See https://developer.mozilla.org/cs/docs/Web/JavaScript/Reference/Statements/for...in
Just try to replace for loop with this
for (let key in returnResult['cart']){
console.log(returnResult['cart'][key]['cartQuantity']);
}

Issues getting JSON object array values when they are an integer

I'm trying to make a function that iterates through all the objects in an array returned to me by the server. Here's the structure that is listed when I console.log my response.
Now I made a javascript function that looks like this—
var createPosts = ((data) => {
var postsArrayLength = data.response.total_posts;
for ( i = 0; i < postsArrayLength; i++ ) {
//for each post create a div
var postDiv = document.createElement('div');
postDiv.className = 'post ' + data.response.posts.postsArrayLength[i].type;
}
});
and I'm receiving this error—
Uncaught TypeError: Cannot read property '0' of undefined
It seems to only be giving me this error when I try to get an object that has an integer as its name.
Is there a way to deal with this? Or am I going about this completely wrong? Thanks!
Rewrite your function to something like this:
var createPosts = data => {
for ( i = 0; i < data.response.posts.length; i++ ) {
//for each post create a div
var postDiv = document.createElement('div');
postDiv.className = 'post ' + data.response.posts[i].type;
}
};

Retrieving a variable from within a function

I am attempting to pull information from the League of Legends API.
To simplify what I am doing, I am attempting to pull information about a user and their previous matches. The problem that I run into is that when I parse a JSON request, it returns a champion ID rather than their name (Ex: 412 rather than "Thresh").
The only solution I can see for this would be to make another JSON request and parse that data for the champion name. Currently what I have looks like this.
$.getJSON(championMasteryPHP, function (json) {
for (var i = 0; i < 20; i++) {
var champID = json[i].championId;
var championInfo = "http://example.com/champInfo.php?summonerid=" + champID;
$.getJSON(championInfo, function (json2) {
var champName = json2.name;
});
$('#champ').append("<li>"+champID+" - "+champName+"</li>")
}
});
I'm unable to access the champName variable due to it being nested within the second JSON function.
Is there a better way to do this?
$.getJSON(championMasteryPHP, function (json) {
for (var i = 0; i < 20; i++) {
var champID = json[i].championId;
var championInfo = "http://example.com/champInfo.php?summonerid=" + champID;
$.getJSON(championInfo, function (json2) {
var champName = json2.name;
$('#champ').append("<li>"+champID+" - "+champName+"</li>")
});
}
});
Just put it inside the second json request since you need to wait till that request is done anyway.
You should put the append statement in the callback because getJSON is an asynchronous method (does mean the Request is running in the background, and calls your function back when it got a response), so you should wait for the response first then you can append it to #champ :
$.getJSON(championMasteryPHP, function (json) {
for (var i = 0; i < 20; i++) {
var champID = json[i].championId;
var championInfo = "http://example.com/champInfo.php?summonerid=" + champID;
$.getJSON(championInfo, function (json2) {
var champName = json.name;
$('#champ').append("<li>"+champID+" - "+champName+"</li>")
});
}
});
Hope this helps.

Call Javascript callback in a loop

I'm a javascript newbie and has been given a problem to solve so i really need your help.
The problem is this:
I have a loop of companies list. For each company I need to make a ajax call like below.
My problem is that I want to stay in the loop and just get the value that the ajax call return so I can use that value there. Now I get the return value to the getData method. How can I solve this?
for (var j = 0; j < companiesToList.length; j = j + 1) {
getCompanyData(companiesToList[j].id, numberArray, function(data){
getData(data)
}
}
var getCompanyData = function(companyid, numbers, callback) {
var baseUrl = '../data/financial/company/';
baseUrl += companyid + '/';
numbers = numbers.distinct();
baseUrl += numbers.join(',');
tiger.ajax.core.getJSON(baseUrl, null, function(data) {
callback(data.financial);
});
};
A good way to solve this is with promises, using a library like kriskowal's Q (or any other interface that implements the promise API):
for (var j = 0; j < companiesToList.length; j = j + 1) {
getCompanyData(companiesToList[j].id, numberArray, function(data){
getData(data).then(function(result) {
// do something with result asynchronously
}
}
}
var getCompanyData = function(companyid, numbers, callback) {
// create a deferred object to return
var deferred = Q.defer();
var baseUrl = '../data/financial/company/';
baseUrl += companyid + '/';
numbers = numbers.distinct();
baseUrl += numbers.join(',');
tiger.ajax.core.getJSON(baseUrl, null, function(data) {
// resolve the promise with the retrieved data
deferred.resolve(data.financial);
});
// return the unresolved promise immediately
return deferred.promise;
};
Whether the above will work out of the box for your situation depends on what exactly you need to do inside the loop after the results come back, since if you want to be picky you aren't actually staying inside the loop, but using then as a callback (if you will) to execute code after the result is retrieved. That being said, the above pattern works well in a lot of situations like this. I can edit my answer if you provide more information about what you need to do with the data.

How to access members of a object in node.js

I'm really new to node.js and having a bit of a problem with objects. Lets say I have two files, one called printer.js and another called database.js. printer.js prints the results database returns. printer.js looks like this:
var db = require("./database")
db.getStations(dbReturn);
function dbReturn(stations) {
for(var i = 0; i < stations.length; i++) {
console.log('id: ' + stations.id);
}
}
and my database.js looks like this:
function getStations(callback){
var listOfStations = [];
for(var index = 0; index < 10; index++) {
var station = new Station(index);
listOfStations[index] = station;
}
callback(listOfStations);
}
function Station(id){
this.id = id;
}
exports.getStations = getStations;
I would just like to mention that Station class has a lot more members than that. But the problem here is that I cannot access the members from the Station objects I created in database.js from printer.js. I am having quite a bit of trouble figuring out how to do this. I have learned how to create a new object of Station in printer.js by exporting Station, but I still can't access the members of an object I created somewhere else! It just spits out 10 x "id: undefined"
I have been suggested to do something similar to this:
database.prototype.getStations = function(callback) {
//...
}
database.prototype.Station = function(id) {
//...
}
module.exports = database;
But this does not seem to work since it just tells me that database is undefined. What am I doing wrong here?
You're not accessing the stations by index in your for loop.
Change this in printer.js:
console.log('id: ' + stations.id);
to:
console.log('id: ' + stations[i].id);

Categories