"Preventing Cross-Origin Requests" error encountered while trying to load a JSON document

I've been working on an online experiment using JavaScript, and I need to load parameters for the task from a JSON file. I managed to do this successfully when running the task through a live server. However, if I try to run it locally by opening the index.html file, I encounter the following error:

Cross-Origin Request Blocked: The Same Origin Policy prevents reading the remote resource at file:///home/terraregina/Desktop/Space_Adv_Behav_PIlot_Online/config.json. (Reason: CORS request not http).

Here's my code for loading the JSON file:

$.ajax({
    dataType: "json",
    url: "config.json",
    success: function(data) {
        assignValues(data);   // extracting values from JSON file
        main();               // executing the experiment
    }
});

Do you have any suggestions or solutions? Thank you.

Answer №1

[ EDIT ]

Some current web browsers, such as Chrome, restrict access to local files using Javascript with the file: scheme. Instead, you can set up a simple web server to share it. You may utilize libraries like http-server for this purpose.

Examples

  1. Using NodeJS & NPM
npm i -g http-server
http-server your_config_folder
  1. Using PHP (Run this inside your folder)
php -S localhost:8080
  1. Using Python 3 (Run this inside your folder)
python -m http.server 8080

Then, you can access the config.json file from your web browser:

http://localhost:8080/config.json

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

I was disappointed by the lackluster performance of the DataTable in CodeIgniter; it did not

I recently started using CodeIgniter and I'm having trouble getting the dataTable to work. Here's a snippet of my page: <table class="table table-striped table-bordered table-hover dataTables_default" id="dataTables-example"> ...

Unable to insert the string into the database: BaseXException: Name '' is considered invalid

Once I successfully input valid XML from a file into BaseX, how can I now add valid XML from a String? thufir@dur:~/NetBeansProjects/twitterBaseX$ thufir@dur:~/NetBeansProjects/twitterBaseX$ basex BaseX 9.0.1 [Standalone] Try 'help' to get more ...

Having trouble implementing pagination for news-api in Vue.js2?

I am currently working on implementing a basic pagination feature in my Vue component specifically for the newsapi.org API. While my initial API call in the created hook is functioning as expected, I am encountering difficulties navigating to different pa ...

I must address the drag-and-drop problem in reverse scenarios

I am currently utilizing react-dnd for drag and drop feature in my color-coding system. The implementation works flawlessly when I move a color forward, but encounters an issue when moving backward. Specifically, the problem arises when shifting a color ...

Error encountered in Django due to repeated AJAX calls causing a closed socket issue: [WinError 10053] The established connection was abruptly terminated by the software running on your host machine

Trying to integrate live search functionality using the Select2 jQuery plugin in my Django 1.11.4 project has led to some server-related issues. Upon entering text into the search box, the server seems unable to handle the volume of requests and ends up sh ...

Binding data to custom components in Angular allows for a more flexible

In my current scenario, I am looking to pass a portion of a complex object to an Angular component. <app-component [set]="data.set"></app-component> I want the 'data.set' object in the parent class to always mirror the 'set&apo ...

Struggling to troubleshoot issues with asynchronous tasks in Angular? Encountering timeouts while waiting for elements on an Angular page? Learn

Edit: I have identified the source of my issue with guidance from @ernst-zwingli. If you are facing a similar error, one of his suggested solutions might be beneficial to you. My problem stems from a known Protractor issue itself. For those who suspect the ...

Tips for organizing static JSON files for XCTests

Currently, I have a collection of static json files within my project that I am utilizing in unit tests instead of API responses. In order for this setup to function properly, the target membership of these files must belong to the production target; other ...

Directing to index.html using ExpressJS

JS, I am working on an express app that has various routes defined. However, I am facing an issue where if the router does not match any route, it displays index.html instead of redirecting to a specific route like '/*' as I expected. I am unsu ...

Retrieve the offspring with the greatest level of depth within a parental relationship

Consider the following tree structure: -root | | |-child1 | |-innerChild1 | |-innerChild2 | |-child2 I am looking to create a JavaScript function that can determine the depth of an element within the tree. For example: var depth = getInnerDepth( ...

Ways to incorporate a php file based on the user's selection

I have numerous div elements, possibly a dozen or two, such as... <div class="mydivs" id="firstdiv"></div> <div class="mydivs" id="seconddiv"></div> <div class="mydivs" id="thirddiv"></div> <div class="mydivs" id="fo ...

Implement seamless content loading using jQuery, eliminating the need

Is there a reason why this piece of code isn't working for me? I'm trying to load HTML content using jQuery and followed the instructions from this tutorial: Here's how my HTML looks: <div id="icon"> <a href="http://localhost/ ...

Troubleshooting a 404 error for an existing object: What to do?

I encounter a 404 'Not Found' error when attempting to edit a mark through my form. I am puzzled by the source of this error because in order to access this form, I require the brand ID (which can be found in the URL). Upon accessing my modifica ...

JavaScript for rotating an element upon button click

My webpage design <div id="yabanner"> <img src="img/ok.jpg"> </div> <button>Click Me</button> <button>Click Me</button> <button>Click Me</button> My script code var button = document.getElementsBy ...

Can Chrome Support Bookmarklets?

While attempting to craft a bookmarklet in Chrome using the console, I encountered the following error: Refused to load the script 'https://code.jquery.com/jquery-1.6.1.min.js' because it violates the following Content Security Policy directive: ...

What is the best method for verifying that audio has not been loaded correctly?

After creating a script to scrape for mp3 audio file URLs and load them into my HTML audio element's src, I encountered an issue where some of the URLs were not functioning properly. As a result, the audio was unable to execute the load() method since ...

The Express GET route does not support parameters or additional paths

I am facing an issue with making a fetch request when trying to add additional path or parameters... Here is what I want to achieve: const fetchOwnerCardList = () => { fetch("http://localhost:5000/api/card/ownerCards", { method: "GET", header ...

Swap out a module with a different one in a node.js environment

In the scenario where a node.js application consists of numerous files referencing a particular module (like underscore), and there is a need to replace that module with another (such as lodash), the typical approach involves globally replacing the names a ...

Utilize Javascript to Populate Form Fields Based on "Selected Name"

I am currently facing a challenge in using javascript to automatically populate a form, specifically when it comes to setting the value for the country field. <form action="/payment" method="post" novalidate=""> <div class="input_group"> ...

display and conceal elements according to the slider's current value

Currently, I am working on creating a slider that can show and hide elements as the slider bar moves (ui.value). Firstly, I used jQuery to create 30 checkboxes dynamically: var start = 1; $(new Array(30)).each(function () { $('#showChck') ...