简体   繁体   中英

“Cross-Origin Request Blocked” error when loading a JSON file

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.

[ 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM