Caching effect on CORS: No 'Access-Control-Allow-Origin' header is present on the requested resource

后端 未结 6 1271
故里飘歌
故里飘歌 2020-12-02 09:05

The short version of this issue is we are seeing the typical CORS error (x has been blocked by CORS policy: No \'Access-Control-Allow-Origin\' header is present on the

6条回答
  •  温柔的废话
    2020-12-02 09:51

    https://assets-frontend.kalohq.ink/style.allapps.add899080acbbeed5bb6a7301d234b65.css only returns CORS headers when an "Origin" header is present (which is sent with a CORS request, but not regular requests).

    Here's what happens:

    1. User fetches CSS as part of a no-CORS request (eg, ). This caches due to the Cache-Control header.
    2. User fetches CSS as part of a CORS request. The response comes from the cache.
    3. CORS check fails, no Access-Control-Allow-Origin header.

    The server is at fault here, it should use the Vary header to indicate its response changes depending on the Origin header (and others). It sends this header in response to CORS requests, but it should send it in response to non-CORS requests too.

    Chrome is somewhat at fault here, as it should use the credentials mode of the request as part of the caching key, so a non-credentialed request (such as those sent by fetch()) shouldn't match items in the cache that were requested with credentials. I think there are other browsers that behave like Chrome here, but Firefox doesn't.

    However, since you're using a CDN, you can't rely on browsers to get this right, as the caching may still happen at the CDN. Adding the correct Vary header is the right fix.

    tl;dr: Add the following header to all of your responses that support CORS:

    Vary: Origin, Access-Control-Request-Headers, Access-Control-Request-Method
    

提交回复
热议问题