0

I have an online implementation of an experiment in javaScript and it has to load the parameters for the task implementation from a JSON file. I found a way to do this but it works only when I run the task through a live server. If I run locally by opening the index.html file, I get the following error:

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

My code for loading the JSON file is:

$.ajax({
    dataType: "json",
    url: "config.json",
    success: function(data) {
        assignValues(data);   // extract vals from JSON file
        main();               // run experiment
    }
});

Any suggestions? Thank you.

  • Does this answer your question? [XMLHttpRequest issue: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https](https://stackoverflow.com/questions/60786555/xmlhttprequest-issue-cross-origin-requests-are-only-supported-for-protocol-sche) – Edric Jun 22 '20 at 15:49
  • If you aren't familiar woth CORS I recommend you read up on it. E.g. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS. It's there to protect you but can be disabled for certain scenarios. – Anton Jun 22 '20 at 15:51
  • Run a local server! – epascarello Jun 22 '20 at 15:54
  • @Edric I think I do essentially have the same problem but the solution is again to use a server. When I do that, everything runs fine and the final version will be run on a server framework anyways but until then I want to be able to run it locally too for certain reasons. – terraregina Jun 22 '20 at 17:07
  • @epascarello, am I to understand that it is not possible to run it locally at all? Thanks to everyone for the quick responses. – terraregina Jun 22 '20 at 17:08

1 Answers1

2

[ EDIT ]

Some modern browsers like Chrome prohibit to access local file with Javascript using file: scheme. Instead, You can use a simple web server to expose it. You can use some library like http-server to expose your local file.

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

And then access config.json file from web browser:

http://localhost:8080/config.json

  • I'm a bit confused, my problem is that my task doesn't run when I open it locally (not through a server). Does your answer still apply? Thank you. – terraregina Jun 22 '20 at 17:03