猿问

加载 JSON 文件时出现“Cross-Origin Request Blocked”错误

我在 javaScript 中有一个实验的在线实现,它必须从 JSON 文件加载任务实现的参数。我找到了一种方法来做到这一点,但它只有在我通过实时服务器运行任务时才有效。如果我通过打开 index.html 文件在本地运行,则会收到以下错误:


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).

我加载 JSON 文件的代码是:


$.ajax({

    dataType: "json",

    url: "config.json",

    success: function(data) {

        assignValues(data);   // extract vals from JSON file

        main();               // run experiment

    }

});

有什么建议么?谢谢你。


九州编程
浏览 290回答 1
1回答

海绵宝宝撒

一些现代浏览器(如Chrome )禁止使用Javascript使用file:方案访问本地文件。相反,您可以使用简单的 Web 服务器来公开它。您可以使用诸如http-server 之类的库来公开您的本地文件。例子使用 NodeJS 和 NPMnpm i -g http-server http-server your_config_folder使用 PHP(在你的文件夹中运行它)php -S localhost:8080使用 Python 3(在你的文件夹中运行它)python -m http.server 8080然后config.json从网络浏览器访问文件:http://localhost:8080/config.json
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答