1

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.

5
  • Does this answer your question? XMLHttpRequest issue: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https Commented Jun 22, 2020 at 15:49
  • If you aren't familiar woth CORS I recommend you read up on it. E.g. developer.mozilla.org/en-US/docs/Web/HTTP/CORS. It's there to protect you but can be disabled for certain scenarios. Commented Jun 22, 2020 at 15:51
  • Run a local server! Commented Jun 22, 2020 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. Commented Jun 22, 2020 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. Commented Jun 22, 2020 at 17:08

1 Answer 1

3

[ 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

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.