"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

Why is the Twitch api map function returning nothing, while the console log is showing output?

Presently, my Nextjs page is making multiple Twitch API calls successfully and displaying the correct data. However, one of the mapping functions is failing to render anything on the page, even though the console log shows the data. Although I am relativel ...

The functionality of Bootstrap popover is not functioning properly

I'm trying to activate a popover when users hover their mouse over a div. Can I use a popover with a div, or am I missing something in my code? Here's what I have: <div class="grid-item content-text" data-toogle ="popover" data-content="Lorem ...

Create an interactive Angular form that dynamically generates groups of form elements based on data pulled from

I am currently developing an Angular application and working on creating a dynamic form using Angular. In this project, I am attempting to divide the form into two sections: Person Name and Personal Details. While I have successfully grouped fields for P ...

Using JQuery for sending POST requests in JavaScript

I am currently facing an issue while trying to post JSON data to a server. I have managed to do it successfully using a certain method, which is as follows: <html> <head> <script src="http://code.jquery.com/jquery-latest.min.js">< ...

Node.js - utilizing Express for handling raw request bodies

Recently, I was developing a RESTful API with the intention of being able to receive raw JSON data for compatibility with mobile applications, and then store this data in my MongoDB database. However, I've encountered a challenging issue that I just ...

How to direct all wildcard paths to a particular route in Next.js

I currently have a single landing page application built with nextJs. I am wondering if it is possible to redirect all paths to specific routes, similar to how we do it in react-router. How can I achieve the same functionality in nextJs? <BrowserRou ...

Namespace remains ambiguous following compilation

I'm currently developing a game engine in TypeScript, but I encountered an issue when compiling it to JavaScript. Surprisingly, the compilation process itself did not throw any errors. The problem arises in my main entry file (main.ts) with these ini ...

Struggling with converting 11-line toy neural network code into JavaScript

I'm preparing to deliver a brief presentation on neural networks this coming Tuesday to my fellow web developer students. My plan was to convert this code (found under Part 1, a tiny toy neural network: 2 layer network) into JavaScript so that it woul ...

Utilizing Django models to populate Google Charts with data

I am currently working on showcasing charts that display the most popular items in our store. To achieve this, I need to extract data from the database and incorporate it into the HTML. Unfortunately, the charts are not loading as expected. When testing wi ...

Update the chosen option in a dropdown list with jQuery and javascript

I need to set the value of a column in a repeater so that once it's assigned, the column will display the current selection from the dropdown. I have the correct value to assign in $('#myname_' + rowIndex).text(), but when I try to assign t ...

Problem with React Router: Uncaught Error - Invariant Violation: The element type is not valid, a string is expected for built-in components

I am encountering an issue with react-router and unable to render my app due to this error. Here is a screenshot of the error I have searched extensively for a solution but have not been able to find anything useful. Any help would be greatly appreciated ...

The method of implementing an index signature within TypeScript

I'm currently tackling the challenge of using reduce in Typescript to calculate the total count of incoming messages. My struggle lies in understanding how to incorporate an index signature into my code. The error message that keeps popping up states: ...

React component rendering twice due to width awareness

In a React component that I've developed, I have utilized ResizeObserver to track its own width. Within this component, two divs are rendered with each having a "flex: 1" property to ensure equal width distribution. Under certain conditions, such as w ...

clicking on internal links in the bootstrap side menu causes it to jump

Im trying to add a side menu to a help page. The menu and internal links are functioning properly, but when clicked, the side menu partially goes behind the navbar. As a beginner, I'm not sure how to resolve this issue. Can someone offer some guidan ...

How can I efficiently update Vue data externally?

const app = createApp({ data() { return { unique_id: 0 } } }) I implemented an autocomplete feature on a specific input field. My goal is to send the chosen id to a Vue application when a label is selected. onSelectItem: ({label, value}) ...

Choosing a single radio button value within a nested ng-repeat loop in AngularJS

Help needed with selecting only one radio button value in nested ng-repeat. Please review the source code and suggest any potential mistakes. <form ng-submit="save()"> <div ng-repeat="x in surveyLst"> <div class="row"> < ...

Dynamic resizing navigation with JQUERY

I have successfully created a navigation menu that dynamically resizes each list item to fit the entire width of the menu using JavaScript. $(function() { changeWidth(500); function changeWidth(menuWidth){ var menuItems = $('#menu l ...

Breaking down the jQuery datepicker into individual fields for Day, Month, and Year

Currently, I am using the Contact Form 7 plugin on my Wordpress website, which I believe uses the jQuery datepicker for its date fields (please correct me if I'm mistaken). My query is about splitting the user input box into three separate elements ( ...

Exploring real-time data updates using React and the setInterval method

Every time my component loads, I am attempting to continuously poll the Spotify API using setInterval. However, during testing, an error message pops up: Invalid Hook Call..etc. I suspect that the issue stems from using useEffect within another useEffect w ...

What is the best way to store a JavaScript variable in a SESSION for seamless pagination implementation?

I'm working on a website where I need to adjust the number of visible items on the screen based on the screen size. Specifically, I have a gallery that should only display as many images as can fit on the screen at once. To achieve this, I've al ...