Search code examples
corsaws-api-gateway

Though 'Access-Control-Allow-Origin' header present in options response , stilll getting cors error


I made request to
curl -v -X OPTIONS 'https://mydomain/v0/countries' --header 'Authorization: Bearer my_token'

In response header following I can see :

< HTTP/2 200 
< content-type: application/json
< content-length: 0
< date: Tue, 14 Jul 2020 15:26:10 GMT
< x-amzn-requestid: 1b2cc673-c84c-4949-bfc7-8340f50302c0
< access-control-allow-origin: *
< access-control-allow-headers: Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With
< access-control-request-headers: *
< x-amz-apigw-id: Pq029F_LDoEFsag=
< access-control-allow-methods: POST, OPTIONS, GET, PUT
< x-amzn-trace-id: Root=1-5f0dce92-3d4fb21c641373a4d3267554;Sampled=0
< access-control-allow-credentials: true
< x-cache: Miss from cloudfront
< via: 1.1 67e2031fa6e0a594e0371c2f15a6997b.cloudfront.net (CloudFront)
< x-amz-cf-pop: BLR50-C3
< x-amz-cf-id: LgRzPra6p1aAhncJDrVB937TVrbWy8igEnl4EF3jrPY1IqDbS8Z91g==

But when I made the request from chrome's developer console using :

(async function getData(url = '') {
  const response = await fetch(url, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer my_token'
    }
  });
  return response.json();
})('https://mydomain/v0/countries')

Following error I can see:

Access to fetch at 'https://mydomain/v0/countries' from origin 'https://www.google.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I am not sure what is going wrong here. Could anyone please help.


Solution

  • When browser make the OPTIONS call to the server , browser doesn't send a bearer token .

    This will be something like

    curl -X OPTIONS https://mydomain/v0/currencies -i
    

    Which was returning 401 in my case and not setting the headers. But I haven't realized it, as I always making curl request with a bearer token , until one of my colleague pointed this out.

    Now removed authentication check for OPTIONS call and its working fine.