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

后端 未结 6 1265
故里飘歌
故里飘歌 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

    We experienced the same problem when migrating our JS to Webpack.

    Our setup is similar:

    • assets are uploaded to an S3 bucket during deployment
    • the bucket is set as the Cloudfront origin

    When migrating to Webpack, we wanted to take advantage of JS sourcemaps for better error reporting to Airbrake. To allow errors to be catched properly, the crossorigin="anonymous" attribute had to be set on the script tags. The reason why is explained here: https://blog.sentry.io/2016/05/17/what-is-script-error.html

    Part of the problem was that CORS response headers were sometimes returned, sometimes not, triggering a CORS errror in the browser. Cloudfront servers were caching the response with OR without the CORS headers, depending on the first client request making a Miss request.

    So two possible outcomes:

    1. First client does not send the Origin request header => Cloudfront server caches the response without CORS headers.
    2. First client sends the Origin request header => Cloudfront server caches the response without CORS headers.

    This made the problem look like it was random, but it was just a matter of race condition (how the first client made the request) and different headers cached on different Cloudfront servers: timing and location dependent. Add to that the fact that browsers might cache these wrong headers...

    So you need to properly configure Cloudront's distribution behavior to:

    • allow and cache preflight (OPTIONS) requests
    • base the cache on CORS request headers (Origin, Access-Control-Request-Headers, Access-Control-Request-Method)

    Here is the configuration that solved our problem.

    S3 bucket / Permissions / CORS configuration:

    
    
    
        *
        GET
        HEAD
        300
        *
    
    
    

    Cloudfront distribution / Edit Behavior:


    We now experience a problem similar to yours, as we just migrated our CSS to Webpack. We are experiencing even more sporadic CORS errors for CSS files. We are trying to remove the crossorigin="anonymous" attribute on tags since we don't need error tracking for CSS files.

提交回复
热议问题