Search code examples
javascriptcorsfetch-apigithub-pagesliveserver

Javascript fetch giving CORS error despite using GH pages and CORS Proxies


I am working on a virtual piano application, and I'm having a lot of issues with trying to fetch audio files from github. Specifically, I keep getting the errors

Access to fetch at 'https://github.com/benvessely/virtual-piano/blob/main/sounds/c4-virtual-piano.mp3' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

GET https://github.com/benvessely/virtual-piano/blob/main/sounds/c4-virtual-piano.mp3 net::ERR_FAILED 200 (OK)
@ piano.js:57 ready  

Uncaught (in promise) TypeError: Failed to fetch at createAudioBuffers (piano.js:57:26) at ready (piano.js:28:26) at piano.js:13:5

In my code, I am simply calling fetch via

const c4AudioURL = "https://github.com/benvessely/virtual-piano/blob/main/sounds/c4-virtual-piano.mp3";   
const c4AudioFetch = fetch(c4AudioURL);  

I am using Live Server on VSCode, so I tried to deploy my site to GH Pages to see if that would fix things, but I still got the errors. I also tried two different CORS proxies, one being crossorigin.me and my code changing to

const c4AudioURL = "https://crossorigin.me/https://github.com/benvessely/virtual-piano/blob/main/sounds/c4-virtual-piano.mp3";   

and the other changing my code to

const c4AudioURL = "https://corsproxy.io/https://github.com/benvessely/virtual-piano/blob/main/sounds/c4-virtual-piano.mp";  

Am I missing something here? I suppose It's that possible that I'm missing something in my code or in the way I'm using Github, as I'm a pretty inexperience programmer. I've been stuck on this for a while, so I appreciate any ideas you might have!


Solution

  • Use local / server-relative paths. For example, say your directory structure looks like this...

    .
    ├── index.html
    ├── piano.js
    └── sounds
        └── c4-virtual-piano.mp3
    

    With either LiveServer serving this directory or deploying it to Github Pages, you can fetch assets without going cross-origin

    const res = await fetch('sounds/c4-virtual-piano.mp3');
    

    That way it will work wherever you run it, as long as you publish your MP3 files when deploying to Github pages. Then you won't need to worry about CORS at all