Chrome瀏覽器HTML支援本地(file協議)的AJAX請求
在執行html demo頁面時,當demo頁面中使用file來引入js(jQuery)來進行ajax請求資源時,會出現如下錯誤:
Access to XMLHttpRequest at 'file:///Users/zzs/develop/softs/dwz/dwz_jui/dwz.frag.xml?_=1553419402393' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
原因很簡單,瀏覽器(Webkit核心)的安全策略決定了file協議訪問的應用無法使用XMLHttpRequest物件。嘗試了一下Firefox瀏覽器,沒有發現此問題。
跨域請求僅支援協議:http, data, chrome, chrome-extension, https, chrome-extension-resource
解決方法
設定Chrome瀏覽器,讓其支援file協議的方案。
Windows下:
設定Chrome的快捷方式屬性,在“目標”後面加上–allow-file-access-from-files,注意前面有個空格,重新開啟Chrome即可。
Mac下:
1、建立MyChromeDevUserData資料夾,用來儲存關閉安全策略後的使用者資訊的,名字可以隨意取,位置也可以隨意放。
2、關閉安全策略程式碼
開啟命令列視窗,執行如下命令。注意,此處需要修改對應路徑。
open -n /Applications/Google\ Chrome.app/ --args --disable-web-security--user-data-dir=/Users/LeoLee/Documents/MyChromeDevUserData

回車之後,Chrome會彈出如下視窗:

重新開啟瀏覽器,即可正常訪問:
