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();
Related
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.");
});
});
}
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
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?
Just learning Sails.js so go easy on me.
I have queried an XML service and successfully jsonified it using xml2js
var req = https.request(options, function(res) {
var xml = '';
res.on('data', function(chunk) {
xml += chunk;
});
res.on('end', function () {
var result = parseString(xml, function (err, result) {
console.log(JSON.stringify(result)); // Position 1
});
return result;
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.write(data);
var result = req.end();
console.log('Result: ' + JSON.stringify(result)); // Position 2
res.view({ message : 'hello', result : result });
The view is loading fine, and <%= message %> outputs hello. Great.
Position1 console.log is returning the stringified json object - Great.
Position 2 consile.log is returning Result: true - Not good.
I need to be able to get that json data to my view for parsing. How do I do this?
It looks like you're assuming that calling req.end() will give you the response from the https.request you started above. There are a couple of things wrong with that:
req.end() is used to finish writing to an open request, not to get a response. According to the docs, the return value is unspecified.
The https.request call is asynchronous; even if req.end() worked like you want it to, the response wouldn't have come in by the time you call it.
The solution is to put your response code (i.e. your res.view) inside the handler for the end event that you've already written. I'd also recommend refactoring your code to use different variable names for the remote request / response so that they don't collide with the req and res variables in your controller action. The whole thing would then be something like:
myAction: function (req, res) {
// Not sure how you're setting options, so just an example
var options = {url: 'http://example.com', ...}
var request = https.request(options, function(response) {
var xml = '';
response.on('data', function(chunk) {
xml += chunk;
});
response.on('end', function () {
var result = parseString(xml, function (err, result) {
return res.view({ message : 'hello', result : JSON.stringify(result)});
});
});
});
request.on('error', function(e) {
console.log('problem with request: ' + e.message);
res.serverError(e);
});
}
You might also look into using something like the Request module to simplify your external request; it would save you from having to write event handlers for data and end.
if you want to pass json to some javascript variable:
var clientJsonVar = <%- JSON.stringify(serverSideJson)%>
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);
});
});