How to resolve a Cross-Origin Resource Sharing (CORS) error when trying to access a local JSON file

Currently, I am attempting to use vanilla JS AJAX request in order to retrieve a JSON string from a locally stored JSON file. My main objective is to accomplish this without relying on JQuery. The code snippet below was inspired by this answer. Despite my efforts, I keep encountering an error in the Chrome console (refer to the message provided). Could someone please assist me in identifying where the problem lies? I have experimented with adjusting the positioning of the xhr.open and .send requests but continue to receive error notifications. My suspicion is that the issue may be related to the .send() request?

//Vanilla JS AJAX request to get species from JSON file & populate Select box
function getJSON(path,callback) {

    var xhr = new XMLHttpRequest();                                         //Creating a new request instance

    xhr.open('GET', path ,true);                                            //Preparing asynchronous GET request
    xhr.send();                                                             //Sending the request

    xhr.onreadystatechange = function(){                                    //Checking every change in ready state (0-4)
        if (xhr.readyState === 4) {                                         //Upon completion of request and response readiness
            if (xhr.status === 0 || xhr.status === 200) {                   //Ensuring status is OK (local file or server)
                var data = JSON.parse(xhr.responseText);                    //Parsing returned JSON string
                if (callback) {callback(data);}                             //Executing callback on returned data, if specified
            }
        }
    };
}
//-----------------------------------------------------------------------------

//Testing execution of above function with callback
getJSON('js/species.json', function(data){
    console.log(data);
});

The following error has been raised in the Chrome console:

"XMLHttpRequest cannot load file:///C:/Users/brett/Desktop/SightingsDB/js/species.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource."

I would greatly appreciate any insights into this matter. Thank you.

Answer №1

In essence, as mentioned by Felix and others below, it is not possible to execute an AJAX request on a local file.

Appreciate the feedback.

Answer №2

When testing the application, consider running it on a local server such as apache or wamp to avoid any potential issues.

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

Utilizing Apache POI to style the output within an object

Click here for Excel File referenceHello everyone! I've utilized the code below to read data from an Excel sheet. Can someone assist me in formatting the output data into an object that will generate the specified JSON structure when converted using a ...

I'm curious if someone can provide an explanation for `<->` in TypeScript

Just getting started with TypeScript. Can someone explain the meaning of this symbol <->? And, is ProductList actually a function in the code below? export const ProductList: React.FC<-> = ({ displayLoader, hasNextPage, notFound, on ...

Is there a way to emphasize a particular day on the calendar obtained from the URL?

I have implemented FullCalendar functionality to enable users to select a specific date, retrieve data from a database, and then reload the page with that data. The page is updated with the selected date in the URL. However, when the page reloads, althoug ...

Assistance required for activating an unidentified function or plugin within a Chrome extension

I am currently working on a project involving a chrome extension designed to automate tasks on a specific website. My main focus right now is trying to trigger the click event of a link that has an event handler set up through an anonymous function as show ...

Please indicate the maximum number of digits allowed after the decimal point in the input

My input form uses a comma as the decimal separator: HTML: <form id="myform"> <label for="field">Required, decimal number:</label> <input class="left" id="field" name="field"> <br/> <input type="submit" va ...

Using jQuery, you can activate an onclick function based on specific keywords entered by the user

Within this element, there is a text input field that allows users to search for specific items. Next to the input field is an icon image that can be clicked on to trigger a jQuery onclick event. This event sends an AJAX request to a PHP file, retrieves da ...

Version discrepancy in module metadata

Yesterday everything was running smoothly with Angular 2 and Angular Material, but today I encountered an error when trying to run the program. Can someone please help? ERROR in Error: Metadata version mismatch for module E:/Demo/crud/ node_modules/ ...

Issue with jQuery AJAX request not working as expected

I'm currently utilizing Rapid API to store my users' emails and passwords. Upon clicking, my send function should trigger, however, it seems that the program is not progressing through the AJAX call. I'm at a loss on how to proceed. Any ass ...

Guide on parsing a string that holds multiple JSON objects

My system periodically executes a procedure that captures events from the API using a Timer. However, when trying to serialize the data, I encounter the following error. Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while pars ...

Python faces UnicodeEncodeError when attempting to retrieve a tweet

My current project involves extracting the text of tweets using the Python-based Twittter API. After logging in with oauth, I receive a dictionary that contains the tweet data as follows: jsonTweets = json.loads(response) list = jsonTweets["statuses"] ...

AngularJS allows a function to return an array value, which can be displayed in separate blocks on

Building a program that involves working with an AngularJS array. I need to showcase the elements of the AngularJS array, returned by a function, in an organized manner. Each element should be displayed correspondingly - for example, 'first' cont ...

Material-UI's JSS does not adhere to the justify content property

Having trouble aligning elements in my React app using material-ui 1.0 and its JSS solutions. The code I've written below should center justify, but it's not working no matter how I configure it. I suspect there might be a naming issue since mat ...

searching backwards using regular expressions

I have successfully extracted <%? imagepath;%> using the following regex from a string. <%(\?|.|\s)*%> <img src="http://abc/xyz/<%? imagepath;%>.gif"> <img not_src="http://abc/xyz/<%? imagepath;%>.gif"> <i ...

Learn the step-by-step process of sending an email through the SendGrid API V3 utilizing templates with a comprehensive example

Currently, I am delving into the SendGrid documentation regarding templates and stumbled upon this: You have three options to send transactional templates: Utilizing the SMTP Relay Including the template ID in the templates parameter of the W ...

Tips for adding a "return" button to a page loaded with AJAX

While working with jQuery in prototype to load pages using Ajax, I've come across a feature on big sites like Facebook and Twitter that I'd like to implement: a 'back' button that takes the user back to the previous page when clicked. S ...

Using jQuery and JavaScript to swap images depending on the option chosen in a dropdown menu

On my existing ecommerce website, I have a dropdown menu with the following code: <select data-optgroup="10201" class="prodoption detailprodoption" onchange="updateoptimage(0,0)" name="optn0" id="optn0x0" size="1"><option value="">Please Selec ...

What is the standard approach for exchanging localized user interface strings between Microsoft's MVC and JavaScript?

In the process of developing an application that utilizes a dynamic, javascript-based client, I am facing the need for localization. This particular application includes significant UI components that are not generated by Javascript and are instead served ...

Positioning the div to align perfectly alongside the list items

My current objective involves dynamically creating div elements and populating them with items. A working demo of my progress can be found by following this link. The issue at hand is that the newly created div does not appear in the desired location, but ...

In the event that the final calculated total is a negative number, reset it to zero. Inform the user of an error through the use of a prompt dialog box

I'm having trouble getting the grand total to display as 0 when I enter all amounts in positive values and then change the unit prices to negative values. However, it works fine when I only enter negative values throughout. Can someone please help me ...

Learn the method to conceal rows within a table simply by toggling a button

I need a function that will hide the rows below a row with a header and button, and only reveal them when another row with a header and button is clicked. When one of the +/- buttons is clicked, it should hide or expand all the rows with data content. http ...