0

I made a javascript app that fetch a JSON file when the page load. Everything is working fine for me and most users. But for some people, the fetch request is blocked by CORS because the 'Access-Control-Allow-Origin' header has a value that is not equal to the supplied origin.

enter image description here

you can try here : https://limeshark.dev/editor

My fetch request :

var t = await fetch('https://limeshark.dev/t/', {method: 'GET'});

(I am making the same request on another page (i.e https://limeshark.dev/editor/Neutron) and no one reported this issue)

here is my Express header

app.use(function(req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', 'https://limeshark.dev/');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
    res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, content-type, Access-Control-Allow-Origin');
    res.setHeader('Access-Control-Allow-Credentials', true);
  next();
});

and here is my nginx config

add_header 'Access-Control-Allow-Origin' 'https://limeshark.dev/';
add_header 'Access-Control-Allow-Methods' 'GET, POST';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';    

Of course i noticed that in the error the origin 'https://limeshark.dev' is different from the header value 'https://limeshark.dev/' but i do not know why

thank you in advance :)

YVND
  • 359
  • 3
  • 15
  • 3
    Looks like you're going cross-origin because it's with and without the `www` subdomain. A good way to prevent this risk is to not use absolute paths. For example, your fetch request could just be `fetch('/t/', {method: 'GET'});`. Worth checking this out: https://stackoverflow.com/questions/9370787/access-control-allow-origin-issue-with-and-without-www-in-url – Nick Jun 04 '21 at 20:49
  • 2
    I'm fairly sure that an ***origin*** has **no** trailing `/`. As an aside, if the origin of the request matches the origin of the URL, why do you need CORS at all? Such a response should not need any `Access-Control-*` headers. – spender Jun 04 '21 at 20:52

2 Answers2

0

As suggested by Nick, making the request with a relative path fixed the issue

var t = await fetch('/t', {method: 'GET'});
YVND
  • 359
  • 3
  • 15
0

I could not 'comment' but Nick's answer solved my issue!

Hoodathunk switching the URL would get rid of the dreaded CORS issue...

THANKS NICK! @Nick https://stackoverflow.com/users/6525724/nick

  • Please don't add "thank you" as an answer. Instead, vote up the answers that you find helpful. - [From Review](/review/late-answers/30491243) – Andrey Dec 03 '21 at 12:33