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

本文详细解析了在使用XMLHttpRequest加载本地文件时遇到的跨域问题,并提供了一种解决方案,即通过搭建本地服务器来避免CORS策略限制,确保数据能够被正确加载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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中获取的数据

 

 

 

 

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值