如何解决错误“对于 CORS 请求,URL 方案必须是“http”或“https”。对于此代码

Eli*_*ien 17 javascript fetch promise

它在console.

sandbox.js:1 Fetch API 无法加载 file:///C:/Users/Lizzi/Desktop/novice%20to%20ninja/todos/luigi.json。对于 CORS 请求,URL 方案必须是“http”或“https”

我是aynchronouse编程新手,但我已经阅读了CORS解决方案并尝试了诸如获取 chrome 扩展和禁用 google chrome 的网络安全等方法,但它仍然无法正常工作。

fetch('todos/luigi.json').then((response)=>{
  console.log('resolved',response);
}).catch((err)=>{
    console.log('rejected', err);
});
Run Code Online (Sandbox Code Playgroud)

小智 24

您需要在本地提供 index.html 或将您的站点托管在某个实时服务器上,以便 Fetch API 正常工作。这些文件需要使用 http 或 https 协议提供。

如果您只是从文件资源管理器中单击 index.html,则浏览器会直接从文件系统中获取这些文件。这就是错误显示您计算机上根文件夹的绝对路径的原因。

尝试安装其中之一... - npm serve - Live server (如果您使用的是 Visual Studio Code 的扩展)

或者任何适用于您的环境的服务器。

启动服务器后应该可以正常工作:) 快乐编码!

  • 我在 Visual Studio 代码中使用 liveserver。它有效!您需要安装 LiveServer 扩展,然后右键单击您的 HTML 文件来运行,访问类似 localhost:5500 的页面 (3认同)
  • [您不需要启动服务器](/sf/answers/4194800711/) 如果您启用了 `file://` 请求 (2认同)
  • @Hashbrown 如何做到这一点? (2认同)
  • @Hashbrown 如何启用 file:// 请求? (2认同)
  • @YingStyle Hashbrown 链接的答案对此进行了解释。Fetch 不支持 Chrome 上的 `file://`,但他发布了一个解决方法,因为 XMLHttpRequest 可以工作(如果您 --allow-file-access-from-files)。顺便说一句:如果您在“about:config”中设置“privacy.file_unique_origin=false”,则 Firefox 允许使用“file://”进行 fetch (2认同)