NodeJS - Pass vars between scopes - javascript

I would like to make a GET request to a certain API and pass its response to a method in the outter scope. Is it possible?
var http = require('http'),
magic = new Magic();
http.request('www.random.org/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new', function(response) {
var str = String();
response.on('data', function(chunk) {
str += chunk;
});
response.on('end', function() {
console.log(str);
// here
// magic.load(str);
});
}).end();
// or here
// magic.load(str);
The response str should be passed to magic.load().
I get no errors but the object is not loaded. What am I doing wrong?

Related

Node JS Fetching JSON from url is executing AFTER the rest of the code

I wanted to get a JSON from a URL in my node JS code. The code is working fine, but the sequence of the execution is messed up because of the Async nature of the execution.
var http = require("https");
var number = 37302;
// these functions need to execute is sequence.
console.log('Before API Call');
var response = fetchJson(number);
console.log(response);
console.log('After API Call');
function fetchJson(number)
{
var url = 'https://example.com/api/getactionitems/' + number;
http.get(url, function(res){
var body = '';
res.on('data', function(chunk){
body += chunk;
console.log('JSON Retrieved.');
});
res.on('end', function(){
console.log('Parsing JSON');
var APIResponse = JSON.parse(body);
var Name = APIResponse.EmpName;
var outstring = APIResponse.ActionItem;
return ('Hi ' + Name + ', Your action Items are: '+ outstring);
});
})
.on('error', function(e){
return ("Got an error while fetching data.");
});
}
When this code executes, the sequence of the output strings are as follows:
Before API Call
undefined
After API Call
JSON Retrieved.
Parsing JSON
How can I correct the execution order, so that the sequence are like the following:
Before API Call
JSON Retrieved.
Parsing JSON
<Outpt from the JSON parsing>
After API Call
var http = require("https");
var number = 37302;
// these functions need to execute is sequence.
console.log('Before API Call');
fetchJson(number).then(function(res){
console.log(res);
console.log('After API Call');
}).catch(function(e){console.log('err',e)});
function fetchJson(number)
{
return new Promise(function(resolve,reject){
var url = 'https://example.com/api/getactionitems/' + number;
http.get(url, function(res){
var body = '';
res.on('data', function(chunk){
body += chunk;
console.log('JSON Retrieved.');
});
res.on('end', function(){
console.log('Parsing JSON');
var APIResponse = JSON.parse(body);
var Name = APIResponse.EmpName;
var outstring = APIResponse.ActionItem;
resolve('Hi ' + Name + ', Your action Items are: '+ outstring);
});
})
.on('error', function(e){
reject("Got an error while fetching data.");
});
});
}

How to fix the undefined data when fetching the response data from https request?

I'm getting the value 'undefined' concatenated to my original data when calling the HTTPS response data
This is for calling a URL and getting the response data
```javascript
url = "xxxxxxxx"; //url is anonymous, so cant disclose
function externalApi(url){
try{
var https = require('https');
var request = https.request(url, function (response) {
var str;
var statusCode;
response.on('data', function (data) {
str += data;
statusCode = response.statusCode;
});
response.on('end', function () {
console.log("Data is " +str);
console.log("Status Code is " +statusCode);
});
request.on('error', function (e) {
console.log('Problem with request: ' + e.message);
console.log('Problem with request: ' + e);
});
request.end();
} catch(err){
console.log("the error is" + err);
}
}
I expect the output to be {"MESSAGE":"No log found for ID 2"} but what i get is undefined{"MESSAGE":"No log found for ID 2"}
When you use += with a string, you're concatenating values. [un]Fortunately javascript doesn't blow up when you concat an undefined variable, but it doesn't ignore it either.
In your case, you're declaring var str but you're not initializing it with a value before concat-ing onto it. If you initialize it with a value, ie: var str = '': it would no longer show undefined before the message.
IE:
// your code...
var request = https.request(url, function (response) {
var str = ''; // this way it's not undefined
var statusCode;
response.on('data', function (data) {
str += data;
statusCode = response.statusCode;
});
// the rest of your code...
You are concatenating uninitialized variable with response str += data;.
You should initialize variable as empty string at the beginning.
var str = '';
Change:
str += data;
to:
str = data;

Storing variable value with http.get in NodeJS?

I am having trouble assigning the value to btcprice, when I try to log the variable after the http.get it outputs undefined. I understand that http.get is occurring asynchronously, but don't know what to do in order to fix this. Any help would be great! Thank you.
const http = require('http');
var btcprice;
// request api
http.get(
{
host: 'api.coindesk.com',
path: '/v1/bpi/currentprice.json'
},
function(response){
// get data
let body = '';
response.on('data', function(d) { body += d; });
response.on('end', function() {
// manipulate received data
let parsed = JSON.parse(body);
btcprice = parsed.bpi.USD.rate;
});
})
I've created an example based on your explanation. You can see that the btcprice is only reassigned when the response is fully received before that the btcprice will have the default value undefined.
const http = require('http');
let btcprice;
// request api
http.get({
host: 'api.coindesk.com',
path: '/v1/bpi/currentprice.json'
}, (response) => {
// get data
let body = '';
response.on('data', function(d) {
body += d;
});
response.on('end', function() {
// manipulate received data
let parsed = JSON.parse(body);
btcprice = parsed.bpi.USD.rate;
console.log(btcprice); // btcprice will now have an value
});
})
console.log(btcprice); // btcprice will be "undefined" since the response isn't already available

How to get data from response to get request in node.js?

Trying to make get request from node.js with express module. Here is code of this piece:
var req = http.request(options, function(res) {
res.on('data', function (chunk){
});
});
req.end();
But can't understand how to receive data from responses body, i tried res.body. or res.data. Didn't work.
The data arrives in the chunk parameter. Parts of it anyway. You need to pick up and join all the chunks into a complete response. Copy-paste example from http://docs.nodejitsu.com/articles/HTTP/clients/how-to-create-a-HTTP-request:
var http = require('http');
//The url we want is: 'www.random.org/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
var options = {
host: 'www.random.org',
path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
};
callback = function(response) {
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
console.log(str);
});
}
http.request(options, callback).end();

Http request with node?

How do I make a Http request with node.js that is equivalent to this code:
curl -X PUT http://localhost:3000/users/1
For others googling this question, the accepted answer is no longer correct and has been deprecated.
The correct method (as of this writing) is to use the http.request method as described here: nodejitsu example
Code example (from the above article, modified to answer the question):
var http = require('http');
var options = {
host: 'localhost',
path: '/users/1',
port: 3000,
method: 'PUT'
};
callback = function(response) {
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved, so we just print it out here
response.on('end', function () {
console.log(str);
});
}
http.request(options, callback).end();
Use the http client.
Something along these lines:
var http = require('http');
var client = http.createClient(3000, 'localhost');
var request = client.request('PUT', '/users/1');
request.write("stuff");
request.end();
request.on("response", function (response) {
// handle the response
});
var http = require('http');
var client = http.createClient(1337, 'localhost');
var request = client.request('PUT', '/users/1');
request.write("stuff");
request.end();
request.on("response", function (response) {
response.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});

Categories