Attempt to periodically load remote JSON data (error: Origin is not permitted by Access-Control-Allow-Origin)

My goal is to regularly load a .json file containing some information, and here is the code I have come up with:

var updateIBEX35 = function () {
    var ibexText = document.getElementById("IBEX");

    let url = 'https://www2.ecobolsa.com/js/data/i35.json';
    fetch(url).then(res => res.json()).then((out) => {
        alert(out[0].p); // for debugging purposes
    }) .catch(err => alert(err));
}

var intervalID = setInterval(updateIBEX35, 1000);
// clearInterval(intervalID);

However, I encountered an error which states:

[Error] Origin http://localhost is not allowed by Access-Control-Allow-Origin.
[Error] Failed to load resource: Origin http://localhost is not allowed by Access-Control-Allow-Origin. (i35.json, line 0)
[Error] Fetch API cannot load https://www2.ecobolsa.com/js/data/i35.json. Origin http://localhost is not allowed by Access-Control-Allow-Origin.

By the way, I am using macOS Sierra with Apache, and I attempted to modify the "httpd.conf" or the user file (/etc/apache2/users/Daniel.conf) by adding the following:

Header set Access-Control-Allow-Origin "*"

Unfortunately, the solution did not work as expected :(

Answer №1

Modifying the configuration on your end won't make any difference. The API endpoint you're attempting to access doesn't permit cross-origin requests.

You can either save the data in a local JSON file and then retrieve it, or reach out to the website administrator to enable CORS requests.

Answer №2

It appears that Apache is being used, so if you are also serving PHP pages, why not consider creating a "proxy" that retrieves JSON data and then serves it from the same domain? This approach could effectively resolve your cross-origin issue.

<?php
header('Content-Type: application/json');
echo file_get_contents('https://www.example.com/data/example.json');
?>

Answer №3

Glad to share that I was able to resolve my issue by utilizing jQuery in combination with php:

Below is the content of the js file:

var url = 'https://www2.ecobolsa.com/js/data/i35.json';

var updateIBEX35 = function () {
    $.post('php/decodeJSON.php', { url: url }, function(data) {
        $("#IBEX").text(data);        
    });
}

setInterval(updateIBEX35, 10000);

Here is the content of the decodeJSON.php file:

<?php
    $url = $_POST['url'];
    echo 'IBEX35: '.json_decode(file_get_contents($url))->{0}->{p};
?>

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

Using jQuery along with the jQuery Form Plugin to retrieve and parse the plain text responseText from an Ajax

I am currently working on creating a form using ajaxForm from the jQuery Form Plugin. var options = { target: '#output', // target element(s) to be updated with server response beforeSubmit: beforePost, // pre-submit cal ...

Troubleshooting EACCES issue with Node.js Express app deployed on Heroku and port 80:0.0.0

Trying to deploy a Node application on Heroku has presented some challenges for me. Despite following the recommended steps, I'm encountering errors when attempting to display the app status. Having gone through the Node.js getting started guide on H ...

Is there any purpose to incorporating an AngularJS directive within a comment?

Hello, I'm curious about the purpose of using an AngularJS directive as a comment. I've seen some examples where it can display an alert message, even with arguments, but I'm struggling to see the practical use of a directive as a comment. C ...

reveal the concealed divs within the list elements

html: In my HTML document, I have a unordered list (ul) with each list item (li) constructed like this: <li class="A">list-item <div>1</div> <div class="B">2 <div class="C">3</div> </div> ...

Is there a method to remove a buffer in threejs in order to minimize GPU memory leakage?

I am facing an issue with a large mesh containing over 5 million triangles. I utilized BufferGeometry with attributes such as position, color, normal, and index. However, there comes a point where I need to remove certain indices from the index attribute. ...

The React render function fails to display the components it is supposed to render

Upon running npm start, the browser opens localhost:3000 but only displays a white page. To troubleshoot, I added a paragraph within the <body> tag in index.html. Surprisingly, the text Hello World! appeared for less than a second before disappearing ...

Issue: Unable to deserialize Entities.Student object from START_ARRAY token in com.fasterxml.jackson.databind.JsonMappingException

I am facing an issue with my 'JudoClass' object that holds an arrayList of 'Student' objects. Every time I attempt to create a new student, the error mentioned above pops up. Below is the post method code snippet: @POST @Produces(Medi ...

Loading JSON data asynchronously in iOS devices can be accomplished in a few simple steps

My application extracts information from a Rails app through JSON. I am trying to figure out a way to asynchronously load the JSON data, but I am struggling to implement it due to the complexity of my code. What steps should I take to ensure that my JSON ...

Awesome method of redirecting outdated URLs to the most recent established URL

My website heavily relies on JavaScript and communicates with a .NET C# RPC service. We encountered an issue where clients' browsers cached the JavaScript, so we decided to add a version number to the URL in order to force them to use the latest JavaS ...

Compel instantaneous XMLHttpRequest / Ajax without any prior notification

It's no secret that synchronous XMLHttpRequest has been deprecated due to its negative impact on user experience. The deprecation of Synchronous XMLHttpRequest on the main thread is a result of its adverse effects on end users' experience. For ...

Exploring the process of iterating through a JSON response in PHP to extract all values

{ "ver":2, "inputs":[ { "sequence":4294967295, "witness":"", "prev_out":{ "spent":true, "tx_index":372805487, "type":0, "addr":"3AFgA1pHKrk4jFHwzUL1CKgZvXyFSWZfgD", "value":12712, ...

When utilizing forEach to loop through and interact with elements in React Testing Library, the onClick event handler is not triggered. However, employing a for loop successfully triggers the

In my React project, I've created a functional component called Shop. It accepts a callback function as a prop and displays a list of items. Each item in the list triggers the callback when clicked. function Shop(props) { const { onClickMenu } = p ...

Moving from ngRoute to ui-router in AngularJS is causing a [$injector:unpr] error to be thrown

After switching the routing in my app from ngRoute to ui-router, I encountered two errors: SyntaxError: Unexpected string Uncaught Error: [$injector:unpr] Here is the updated config.route.js: (function () { var app = angular.module('app'); ...

What could be the reason that Vue is not evaluating anything when the directive @click is specified as "true && method"?

Consider the following scenario: LandingPage.vue <template> <button @click="handleClick">Click Me</button> </template> <script> export default { methods: { handleClick() { this.$emit("click"); } } }; < ...

Is it possible for jsonpath-plus to rearrange elements as child elements?

What I have: [ {"Name": "One", "ID": "1", "Child": [ { "ChildName": "Alpha"}, {"ChildName": "Beta"} ] }, {"N ...

Javascript functions properly on Chrome, Opera, and Edge browsers, but unfortunately does not work on FireFox and IE 11

If you're interested, I have some code available on JS Fiddle that showcases my skills. var getJSON = function (url) { "use strict"; return new Promise(function(resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open('get' ...

Is there a way to change HTML retrieved from an AJAX request before inserting it into the document?

I am utilizing an ajax call to retrieve an HTML page from the server; the ajax call is structured as follows: function loadHtml() { $.ajax({ type : 'GET', async : false, url : &apos ...

Sending data from an AJAX POST request to a Grails Controller

Currently, I am in the process of developing a social networking platform using Grails. However, I have encountered a roadblock when it comes to allowing users on their edit profile page to input a YouTube URL into a text field. By clicking a button, a Jav ...

Combine values from a JSON string using a line break

I'm having an issue with my JSON array where each element is not printing on a new line as intended. I attempted to use '/n' and space characters for this purpose but it's not working correctly. String json = null; // Splitting the coo ...

Implement a function to trigger and refresh components in various Vuejs2 instances simultaneously

I currently have index.html with two Vue instances in different files: <!DOCTYPE html> <html lang="en"> <body> <div id="appOne"> </div> <div id="appTwo"> </div> </body> </html ...