javascript 如何解决错误“对于 CORS 请求,URL 方案必须是“http”或“https”。对于此代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/58128248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I resolve the error "URL scheme must be "http" or "https" for CORS request." for this code
提问by Elizabeth Essien
It shows below message in the console.
它在console.
sandbox.js:1 Fetch API cannot load file:///C:/Users/Lizzi/Desktop/novice%20to%20ninja/todos/luigi.json. URL scheme must be "http" or "https" for CORS request
sandbox.js:1 Fetch API 无法加载 file:///C:/Users/Lizzi/Desktop/novice%20to%20ninja/todos/luigi.json。对于 CORS 请求,URL 方案必须是“http”或“https”
I'm new to aynchronouseprogramming but I have read up on CORSsolutions and tried things like getting a chrome extension and disabling web security for my google chrome but it still doesn't work.
我是aynchronouse编程新手,但我已经阅读了CORS解决方案并尝试了诸如获取 chrome 扩展和禁用 google chrome 的网络安全等方法,但它仍然无法正常工作。
fetch('todos/luigi.json').then((response)=>{
console.log('resolved',response);
}).catch((err)=>{
console.log('rejected', err);
});
回答by Nick Sugar
You need to be serving your index.html locally or have your site hosted on a live server somewhere for the Fetch API to work properly. The files need to be served using the http or https protocols.
您需要在本地提供 index.html 或将您的站点托管在某个实时服务器上,以便 Fetch API 正常工作。这些文件需要使用 http 或 https 协议提供。
If you just clicked on your index.html from your file explorer than your browser is grabbing those files directly from your file system. This is why the error is showing you an absolute path from the root folder on you computer.
如果您只是从文件资源管理器中单击 index.html,则浏览器会直接从文件系统中获取这些文件。这就是错误显示您计算机上根文件夹的绝对路径的原因。
Try installing one of these... - npm serve - Live server (an extension for Visual Studio Code if you are using that)
尝试安装其中之一... - npm serve - Live server (如果您使用的是 Visual Studio Code 的扩展)
Or whatever server that will work with your environment.
或者任何适用于您的环境的服务器。
Should work fine once you spin up a server :) happy coding!
启动服务器后应该可以正常工作:) 快乐编码!

