简体   繁体   English

为什么这是跨域请求

[英]why is this a cross domain request

I'm trying to make a set of files to be able to send to someone and they can view some stuff in a web browser locally. 我正在尝试制作一组​​文件以发送给某人,他们可以在本地的Web浏览器中查看某些内容。 My code works when viewed using a web server(apache) but if I load it up just as a file, (ie file:///C:/Code/Web/test/index.html) it get a cross domain request error from my JavaScript file when loading a JSON file. 使用Web服务器(Apache)查看时,我的代码有效,但如果我仅将其作为文件加载(例如file:/// C:/Code/Web/test/index.html),则会收到跨域请求错误从我的JavaScript文件加载JSON文件时。 The HTML, JS, and JSON files are all in the same folder. HTML,JS和JSON文件都在同一文件夹中。 I'm not sure how this is a cross domain request and why chrome and IE fail at loading the JSON file. 我不确定这是一个跨域请求,为什么chrome和IE无法加载JSON文件。 Firefox loads it without problem. Firefox可以毫无问题地加载它。

The JS I use for loading the file is: 我用于加载文件的JS是:

const JSON_FILE = "tin.json";
var xmlhttp;

function webGLStart() 
{
    fetchDoc(JSON_FILE,loadJSON)
}

function fetchDoc(url,cfunc)
{
    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
    xmlhttp.onreadystatechange=cfunc;
    xmlhttp.open("GET",url,false);
    xmlhttp.send();
}

function loadJSON()
{
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
    {
        var input = JSON.parse(xmlhttp.responseText);
        displayData(input);
    }
}

Nothing really happens in my html page. 我的html页面中什么都没有发生。 Its just a canvas where the body calls webGLStart on load. 它只是画布,主体在加载时会调用webGLStart。

Is there a way around this or is this something chrome and IE don't allow? 有没有解决的办法,或者这是Chrome和IE不允许的?

It protects you from attacks such as ones of this form: 它可以保护您免受以下形式的攻击:

  • You receive an email with an HTML document as an attachment 您收到带有HTML文档作为附件的电子邮件
  • You double click the attachment and open the HTML document in your default browser 双击附件,然后在默认浏览器中打开HTML文档。
  • JavaScript embedded in the document accesses files on your hard disk and uploads them to the attacker 文档中嵌入的JavaScript访问硬盘上的文件,并将其上传到攻击者

Chrome and IE ban the access of file scheme URIs outright. Chrome和IE完全禁止访问文件方案URI。 Firefox allows them only if the host URI is in a directory that is a ancestor of the directory contains the target URI. 仅当主机URI在目录中且该目录的祖先包含目标URI时,Firefox才允许它们。


You've already identified the way around it: Host web applications on a web server. 您已经确定了解决方法:在Web服务器上托管Web应用程序。

Browsers have to restrict interaction with local file system due to security reasons. 由于安全原因,浏览器必须限制与本地文件系统的交互。 If you want to test your ajax request, you can set up light http server environment such as lighttpd, node.js npm package http-server or use one of development solutions, such as Microsoft WebMatrix 如果要测试ajax请求,则可以设置light http服务器环境(例如lighttpd,node.js npm程序包http-server)或使用开发解决方案之一,例如Microsoft WebMatrix。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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