ajax(XMLHttpRequest)加载不了本地的文件,Cross origin requests are only supported for protocol schemes: ...

Access to XMLHttpRequest at 'file:///E:/test.txt' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

我原本是做一个flappy bird的,但到加载本地文件的时候,一直报上面的错,就又写了一个简单的ajax请求来看看是怎么回事,看图

目录结构:(够简单了吧,两个数据文件,只用了一个txt文件)

下面是index.html的内容,完全是抄菜鸟教程里的XMLHttpRequest的例子

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <!-- <meta http-equiv="X-UA-Compatible" content="IE=edge"> -->
    <title>Page Title</title>
    <!-- <meta name="viewport" content="width=device-width, initial-scale=1"> -->
    <!-- <link rel="stylesheet" type="text/css" media="screen" href="main.css"> -->
    <!-- <script src="main.js"></script> -->
</head>
<body>
    <button type="button" onclick="loadXMLDoc()">请求数据</button>
    <p>多次点击按钮,可以看到时间变化。</p>
    <div id="myDiv"></div>
    <script>
        function loadXMLDoc()
{
  var xmlhttp;
  if (window.XMLHttpRequest)
  {
    // IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
    xmlhttp=new XMLHttpRequest();
  }
  else
  {
    // IE6, IE5 浏览器执行代码
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function()
  {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
  xmlhttp.open("GET","/test.txt",true);
  xmlhttp.send();
}
    </script>
</body>
</html>

 

运行后,下面是错误提示。

Access to XMLHttpRequest at 'file:///E:/test.txt' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

 

说明不支持file协议的。

解决之一:

    弄一个本地服务器。

因为我是用vscode编写的,这个比较强大。所以,只需要安装插件就可以了。

1、首先,先安装debugger for chrome

2、先根据符号开始,然后在2步骤里选择chrome,就会弹出launch.json文件,

在json文件中添加(一般写完file会自动帮你补全的,如果你有index.html文件)

"file": "${workspaceFolder}/index.html"

选择4中的下拉框的 Launch Chrome against localhost 选项,就会在chrome浏览器弹出一个新的页面,

地址是 "url": "http://localhost:8080"中的地址,显示的页面是index.html这个页面

3、在控制台输入

npm install -g live-server

然后继续输入

live-server

就会弹出一个窗口(这是自动运行的,url地址会被改变,不再是file协议的地址),画线的是从test.txt中获取的数据

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章