尝试从存储在同一目录中的本地 JSON 文件获取一些数据,我得到:
Access to XMLHttpRequest at 'file:///C:/Visual%20Studio%20Code/Practice/customer.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
app.js:14 GET file:///C:/Visual%20Studio%20Code/Practice/customer.json net::ERR_FAILED
有人可以提出解决方案吗?
最佳答案
某些浏览器禁止从本地文件(通过 file:
方案加载的资源)进行任何类型的 ajax。您似乎正在使用其中之一。
解决方案是安装本地网络服务器并通过 http:
加载资源。一些 IDE 直接或通过扩展包含一个最小的 Web 服务器。但如果没有,Apache 或 nginx 的本地安装相当容易安装,或者您可以使用 Express.js 或 Koa.js 或类似的工具自行安装。
这并不是浏览器处理 file:
资源与 http:
/https:
资源方式之间的唯一细微差别,因此当进行 Web 开发时,最好使用本地 Web 服务器,而不是 file:
。
关于javascript - XMLHttpRequest 问题 : Cross origin requests are only supported for protocol schemes: http, 数据、chrome、chrome 扩展、https,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60786555/