skip to Main Content

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 🙂

2

Answers


  1. Chosen as BEST ANSWER

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

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

  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search