CORS header ‘Access-Control-Allow-Origin’ missing
krauss opened this issue · 5 comments
Hey guys, when I try to run a simple fetch to that URL, I get this error back (bottom). Is there anyone else experiencing the same issue? I've been doing some research on it, but it's still not clear to me how to fix it
code:
fetch("https://cfw-takehome.developers.workers.dev/api/variants" { /* properties here */ });
error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://cfw-takehome.developers.workers.dev/api/variants. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
What properties are you passing in?
Following the MDN Web Doc for fecth API, this is my fetch
request:
fetch("https://cfw-takehome.developers.workers.dev/api/variants", {
method: 'GET',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
redirect: 'follow',
referrerPolicy: 'no-referrer'
}).then((response) => {
console.log(response);
return JSON.stringify(response);
//return response.json(); this one returns a weird error
}).then((data) => {
console.log(data)
});
And if I change the mode
parameter to 'no-cors'
, the fetch method does return something but it's an opaque object. Thus, you can't do anything with it. Tha's probably the reason why the json parsing was blowing up. I'm pretty sure I'm missing some parameters in the header, but it's not clear to which ones
Try deploy it onto the worker environment (with the wrangler preview or publish command). I think it's because the API https://cfw-takehome.developers.workers.dev/api/variants isn't configured to support cross origin requests so your fetch request from the localhost will be forbidden. But if you deploy it onto a worker environment it will work fine.
Thank's for your help guys. It's all sorted out.