SOLVED-How do I fix error with access control in web.config file?

徘徊边缘 提交于 2021-01-07 05:03:13

问题


Im getting this error and I don´t know how to fix it.The site is live so therefor I don´t want to test a lot of stuff, breaking it wile testing. I guess the problem is in my web.config file and that its related to the service worker that I use to cache files since that is using "fetch".

The error Im getting.

Fetch API cannot load https://www.google-analytics.com/j/collect?... due to access control checks.
[Error] Failed to load resource: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true.

And the web.config file looks like this.

<httpProtocol>
   <customHeaders>
    <add name="Cache-Control" value="public, max-age=365000000" />
                   
    <!--<add name="Access-Control-Allow-Origin" value="['https://mydomain.se','http://dibspayment.eu','https://checkout.dibspayment.eu','https://www.google-analytics.com']" />-->
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Methods" value="'HEAD,OPTIONS, GET, POST, PUT, PATCH, DELETE'" />
    <add name="Access-Control-Allow-Headers" value="'X-Requested-With, Origin, Content-Type, X-Auth-Token, Accept, Authorization, Content-Length,Access-Control-Allow-Origin, Access-Control-Allow-Methods,Cache-Control'" />
                     
  </customHeaders>
</httpProtocol>

My service worker looks like this.

self.addEventListener('install', function(event) {
    self.skipWaiting() 
  event.waitUntil(
    caches.open('v19').then(function(cache) {
      return cache.addAll([
        '/js/jquery.cookie.js',
        '/js/jquery.sumoselect.min.js',
        '/js/wookmark.min.js',
        '/js/imagesloaded.pkgd.min.js',
        '/js/exif/exif.min.js',
        '/js/exif/load-image.min.js',
        '/js/exif/load-image-scale.min.js',
        '/js/exif/load-image-orientation.min.js',
        '/fonts/Framework7Icons-Regular.woff2',
        '/fonts/Framework7Icons-Regular.woff',
        '/fonts/Framework7Icons-Regular.ttf',
        '/fonts/Framework7Icons-Regular.eot',
      ]);
       //caches.open(v2)
//.then( cache = cache.match('/js/v5/framework7.bundle.min.js'))
//.then( res =res.text())
//.then( js = console.log(js))
    })
  );
});


self.addEventListener('fetch', function(event) {
  if (event.request.clone().method === 'GET') {
    event.respondWith(
      caches.open("v19").then(function (cache) {
        return fetch(event.request).then(function (res) {
        
          cache.put(event.request, res.clone());
          return res;
        })
      })
    )
  } else if (event.request.clone().method === 'POST') {
    // attempt to send request normally
    event.respondWith(fetch(event.request.clone()).catch(function
    (error) {
      // only save post requests in browser, if an error occurs
      //savePostRequests(event.request.clone().url, form_data)
    }))
  }
});

self.addEventListener('activate', function(event) {
  var cacheKeeplist = ['v19'];

  event.waitUntil(
    caches.keys().then(function(keyList)  {
      return Promise.all(keyList.map(function(key)  {
        if (cacheKeeplist.indexOf(key) === -1) {
          return caches.delete(key);
        }
      }));
    })
  );
});

How should I do with the Access-Control-Allow-Origin? I guess that´s where the problem is, or? Any input really appreciated, thanks.

Solution: Ok so I changed it to this so it is not caching google.analytis and the error went away.

self.addEventListener('fetch', function(event) {

if (( event.request.url.indexOf( 'analytics' ) !== -1 ) || ( event.request.url.indexOf( 'checkout' ) !== -1 )){
            
}else{
      if (event.request.clone().method === 'GET') {
        event.respondWith(
          caches.open("v19").then(function (cache) {
            return fetch(event.request).then(function (res) {
            
              cache.put(event.request, res.clone());
              return res;
            })
          })
        )
      } else if (event.request.clone().method === 'POST') {
        // attempt to send request normally
        event.respondWith(fetch(event.request.clone()).catch(function
        (error) {
          // only save post requests in browser, if an error occurs
          //savePostRequests(event.request.clone().url, form_data)
        }))
      }
}
});

回答1:


It's not the issue with yours web.config, but Google Analytics (GA) server's. So you have to adjust requests to meet GA requirements.

  1. GA responses do not want to be cached (underlined in green). All transfer of statistics is done in the send request, the answer is only confirmation of delivery (the text like 1gfr).

  2. GA do not accept requests with credentials (underlined in red) because of:
    - presents of wildcard * in Access-Control-Allow-Origin response header
    - absent of Access-Control-Allow-Credentials: true in responce header

Hence GA wait cross-origin requests with no credentials (no auth cookies should not be sent). The feth() uses mode: 'cors', credentials: 'same-origin' by default (send credentials only to same-origin requests), therefore all should be OK.

But if you still have got CORS error above, it means some browsers send credentials. Try to set Request.credentials to "omit" as recommended by Mozilla.

Or may be it's possible to exclude GA from caching and let process GA requests native way (GA natively use XMLHttpRequest with withCredentials = false option, not fetch()).



来源:https://stackoverflow.com/questions/65094642/solved-how-do-i-fix-error-with-access-control-in-web-config-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!