Reputation: 41
I am having trouble returning a JSON object back to a client upon request - I am just working with the first GET call to '/btc'.
//Main server to recieve requests
http.createServer(function(req,res){
switch(req.method){
case 'GET':
switch(req.url){
case '/btc':
callBtcApi(req,res)
console.log(' btc called');
break;
case '/wallet':
callBtcWallet(req,res)
console.log('wallet called');
break;
case '/weather':
callWeather(req,res);
console.log('weather called');
break
default:
console.log('calling but not hitting');
break;
}
case 'POST':
switch(req.url){
case '/update':
console.log('update called');
break;
}
}
}).listen(3000);
callBtcApi() below, queries a bitcoin API and returns a JSON object successfully (I do intend to do more with the function, just getting the basics down first). callBtcApi() is successfully being called.
function callBtcApi(req,res){
message = '';
https.get('https://api.bitcoinaverage.com/ticker/global/GBP/', function(res){
res.on('data',function(data){
message += data;
});
res.on('end',function(){
console.log('props called ;)');
writeToCLient(res,message);
});
}).on('error', function(e){
console.error(e);
});
}
The issue I am having is when I then pass this data to my writeToCLient() function in res.on('end'). The error i receive in the terminal is
TypeError: res.setHeader is not a function
I know the message is passed into the function writeToCLient() as I am able to see the data in the terminal when I console.log(message) if I temporarurly hide all of the res.() calls.
function writeToCLient(res,message){
console.log(message);
res.statusCode = 200;
res.setHeader('Content-Type','application/json');
res.end(JSON.stringify(message));
}
I have searched google but haven't found anything that explains what could be the issue. Is the issue possibly down to calling a HTTP.get() request from inside callBtcApi() which is sitting inside my main server? Thanks
Upvotes: 0
Views: 1207
Reputation: 1687
Can you try with this?
function callBtcApi(request,response){
message = '';
https.get('https://api.bitcoinaverage.com/ticker/global/GBP/', function(res){
res.on('data',function(data){
message += data;
});
res.on('end',function(){
console.log('props called ;)');
writeToCLient(response,message);
});
}).on('error', function(e){
console.error(e);
});
}
Upvotes: 2