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中獲取的數據