How can I eliminate the unexpected .parse error in the HTTP Request JSON?

For my school project, I am utilizing IBM Bluemix to develop a web service.

The core of my project requires fetching a JSON from an API in order to utilize the provided data.

My main challenge lies in the HTTP request to the API service, as I encounter the following alert in the Windows 10 Command Prompt.

"Syntaxerror: Unexpected Token"

I am aware that there is an issue with my JSON request, but pinpointing the exact problem proves to be difficult.

Provided below is my .js file along with a screenshot displaying the error message upon execution.

/*eslint-env node*/

//------------------------------------------------------------------------------
// Starter application for Bluemix
//------------------------------------------------------------------------------

var http = require('http');
var request = require('request');

var cfenv = require('cfenv');

var express = require('express');

var app = express();

app.use(express.static(__dirname + '/public'));

var appEnv = cfenv.getAppEnv();

app.listen(appEnv.port, '0.0.0.0', function() {
    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("Your quotation is "+cotacao);

});
});

Screenshot of Error in Command Line

Answer №1

Remember to utilize the json object that was created within the .on('end'

Attempting to JSON.parse res when res is clearly not a string is what's causing the error (res.toString() results in [Object object] ... thus triggering the error since that isn't 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 jsonData = JSON.parse(body);
            var exchangeRate = jsonData["bovespa"]["cotacao"];

            console.log("Your exchange rate is "+exchangeRate);
        });
    });
});

Answer №2

Attempt setting up the application to parse JSON bodies:

app.configure(function () {
  app.use(express.json())
})

This will result in receiving a parsed JSON object.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Node.js Decrypts Data Before Sending Response from Database

Issue Update I'm currently facing a challenge in reinserting a decrypted value back into the response after decrypting it. I just need guidance on how to place a value back into the response after manipulation. Scenario Background Within the backen ...

What is the reason behind $('#id').val() not functioning properly when document.getElementById('id').value is working flawlessly?

$('#id').val() = $.cookie("name"); - does not function as expected, no changes occur document.getElementById('id').value = $.cookie("name"); - works properly What is the reason behind this inconsistency? ...

Locating all elements on a webpage that are either above or below a specific element, capturing those that intersect visually

Is it possible to locate all the additional HTML elements that a particular element overlaps with, is positioned under, or intersects with? My goal is to ensure that this element is displayed above every other element. I am looking to identify all interse ...

Using a for loop in Javascript with a specified increment value

I am working with an array containing 100 elements. My goal is to extract elements from the 10th to the 15th position (10, 11, 12, 13, 14, 15), then from the 20th to the 25th, followed by the 30th to the 35th, and so on in increments of 4, storing them in ...

Looking for assistance with aligning the content of an input label using Bootstrap?

Is there a way to adjust the label content if it is larger than the input box size? My goal is to keep all input boxes on the same line while allowing labels to wrap accordingly. https://i.sstatic.net/NrLck.png I'm trying to achieve the alignment sh ...

The error message "Uncaught (in promise) ReferenceError: dispatch is not defined" indicates that

Currently, I am utilizing vuex with index.js and auth.js stored in the store folder. My goal is to perform a basic sign-in operation within my signin.vue by calling an action from the store. However, I encountered the error 'Uncaught (in promise) Refe ...

Error: jQuery is not recognized; There was another issue when including the script

I encountered an issue with the error message: Uncaught ReferenceError: $ is not defined at index.html:76. After researching potential solutions, I found that adding <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> to my < ...

Sign up for our Joomla website by completing the registration form and agreeing to our terms and conditions

I am currently working with Joomla 1.5 and I need to incorporate a checkbox for users to agree to the terms and conditions. I attempted to use the code below, but it is not functioning as expected. Even when the checkbox is ticked, it still triggers an a ...

trouble concerning the responsiveness of a jQuery popup

Hello, I am trying to create a responsive login popup using jQuery but have been struggling for a week. Below is the code snippet that I have been working on. Any help or guidance would be greatly appreciated. //scriptLogin.js archive $(document).ready ...

Troubleshooting Nested Arrays in JavaScript

I have been receiving API JSON data in a specific format and am currently working on reorganizing it. The goal is to group the data first by the start_date and then by the phys_id. The aim is to showcase the available appointment dates followed by each pro ...

Discovering the specifics of an appointment within a shift event using FullCalendar

The title of the question may not accurately depict the scenario I am about to discuss. I'm currently working with FullCalendar and utilizing an open source library that allows me to add resources at the top. You can view the outcome of this on Js ...

Whenever I try to send multiple forms along with their data using JSON/AJAX, I keep running into a parsing

My website features a jQuery accordion plugin. To gather form data from multiple forms, I am using the following code: $('#form_values').val($('form').serialize()). The collected data is then submitted to my PHP file which includes: &l ...

What is the best way to trigger a unique modal dialog for every element that is clicked on?

I simply want to click on the state and have that state's specific pop-up appear. $("path, circle").on('click', function(e) { $('#info-box').css('display', 'block'); $('#info-box').html($(this ...

The attention is consistently drawn to the link within the OffCanvas element

I had successfully created a script that automatically gives focus to a particular element in a popup div when the down key is pressed in a textbox. However, things took a turn when I introduced a sidebar navigation pane using a Bootstrap offcanvas compone ...

Successfully converted Javascript variables to PHP variables, however, I faced difficulties when attempting to compare the PHP variable

When transferring a javascript variable to a php variable, it is typically done using POST or Ajax methods. The code below shows a way to convert the javascript variable to a php variable without relying on POST, Get, or Ajax. When the php variable ...

The term "ArrayList HashMap" does not have a defined

Having trouble understanding why I'm encountering this error message "ArrayList<HashMap<String,String>>, int, String[], int[]) is undefined" // THE ERROR IS RIGHT HERE TO ListAdapter adapter = new SimpleAdapter(this, contactLi ...

Encountered TypeError while attempting to submit form data via Ajax

Attempting to implement form validation using Ajax for real-time feedback without reloading the page. When calling the myAjax function, I pass specific parameters. function myAjax(method, parameters) { var ParametersArray = { "method": method, ...

Sequencing asynchronous operations with node.js using sails.js

When setting up my Sails.js app, I have a series of tasks that need to be executed in order, with each task depending on the successful completion of the previous one. If any task encounters an error, the entire process should stop and prevent the app from ...

Is there a way to keep the modal window open in React without it automatically closing?

I have been working on a modal window implementation in React. I defined a state variable called modalbool to control the visibility of the modal window. The modal window is displayed only when modalbool is set to true. Additionally, I created a parent com ...

Two separate occurrences hold identical values

I'm encountering an issue where instantiating a class two times results in the second instance retaining parameters from the first instance. Here's a simple example: var Test = function() {}; Test.prototype = { bonjour: null, hello: { h ...