Search code examples
javascriptjsonapihttpibm-cloud

HTTP Request JSON: Unexpected .parse error - How do I exterminate it?


I am using IBM Bluemix to make a web service for a school project.

My project needs to request a JSON from an API, so I can use the data it provides.

I am having trouble with the http request to the API service. I get the following alert in the Windows 10 Command Prompt.

"Syntaxerror: Unexpected Token"

I know there is something wrong with my JSON request, but is it exactly?

Here is my .js file and a print of the error screen I get when running it.

/*eslint-env node*/

//------------------------------------------------------------------------------
// node.js starter application for Bluemix
//------------------------------------------------------------------------------

// HTTP request - duas alternativas
var http = require('http');
var request = require('request');

// cfenv provides access to your Cloud Foundry environment
// for more info, see: https://www.npmjs.com/package/cfenv
var cfenv = require('cfenv');

//chama o express, que abre o servidor
var express = require('express');

// create a new express server 
var app = express();

// serve the files out of ./public as our main files
app.use(express.static(__dirname + '/public'));

// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();

// start server on the specified port and binding host
app.listen(appEnv.port, '0.0.0.0', function() {
    // print a message when the server starts listening
    console.log("server starting on " + appEnv.url);
});


app.get('/home1', function(res){
    http.get('http://developers.agenciaideias.com.br/cotacoes/json', function(res){
		var body = '';
		res.on('data', function(chunk){
			body += chunk;
		});
		res.on('end', function(){
			var json = JSON.parse(body);
		});
		var json = JSON.parse(res);
		var cotacao = json["bovespa"]["cotacao"];
	
		console.log("A sua cotação é "+cotacao);
	
	});
});

Print of the Error Screen in the Command Line


Solution

  • You need to use the json object you created in .on('end'

    trying to JSON.parse res when res is clearly not a string is causing your error (res.toString() results in [Object object] ... hence the error as that is not valid JSON

    app.get('/home1', function(res){
        http.get('http://developers.agenciaideias.com.br/cotacoes/json', function(res){
            var body = '';
            res.on('data', function(chunk){
                body += chunk;
            });
            res.on('end', function(){
                var json = JSON.parse(body);
                var cotacao = json["bovespa"]["cotacao"];
    
                console.log("A sua cotação é "+cotacao);
            });
        });
    });