javascript XMLHttpRequest:Access-Control-Allow-Origin 不允许 Origin null

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13143054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:55:37  来源:igfitidea点击:

XMLHttpRequest: Origin null is not allowed by Access-Control-Allow-Origin

javascriptjqueryjsongoogle-chrome

提问by Rocket Hazmat

Possible Duplicate:
XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin
XMLHttpRequest cannot load file://… Origin null is not allowed by Access-Control-Allow-Origin

可能的重复:
XmlHttpRequest 错误:Access-Control-Allow-Origin 不允许 Origin null
XMLHttpRequest 无法加载文件://... Access-Control-Allow-Origin 不允许 Origin null

I am trying to open my JSON file such as:

我正在尝试打开我的 JSON 文件,例如:

jQuery.getJSON('../data/json/en/nodesData.json',
      function(data){
           jQuery.each(data, function(){
                  //do something...
           })
     })

this yields the following error in Chrome:

这会在 Chrome 中产生以下错误:

XMLHttpRequest cannot load file:///C:/URL/data/json/en/nodesData.json. Origin null is not allowed by Access-Control-Allow-Origin

XMLHttpRequest 无法加载 file:///C:/URL/data/json/en/nodesData.json。Access-Control-Allow-Origin 不允许 Origin null

what's problem? How can I retrieve my json?

什么问题?我怎样才能检索我的json?

回答by epascarello

You really should be running a local server like Apache or IIS to run HTML/JavaScript code so you do not run into these restrictions.

您确实应该运行像 Apache 或 IIS 这样的本地服务器来运行 HTML/JavaScript 代码,这样您就不会遇到这些限制。

You can start the browser up with the flag --allow-file-access-from-fileswhich removes the restriction.

您可以使用--allow-file-access-from-files取消限制的标志启动浏览器。

回答by Rocket Hazmat

For security reasons, you cannot make AJAX calls to your local file system. Some browsers allow this, but others don't. Chrome has a flag that enables this, but it's off by default.

出于安全原因,您不能对本地文件系统进行 AJAX 调用。一些浏览器允许这样做,但其他浏览器不允许。Chrome 有一个启用此功能的标志,但默认情况下它处于关闭状态。

回答by Christoph

Take a look into Same Origin Policy.

查看同源策略

You cannot load the file because technically it is located in another domain. You need to call it like localhost/<Path>/nodesData.json.

您无法加载该文件,因为从技术上讲它位于另一个域中。你需要像localhost/<Path>/nodesData.json.