Search code examples
reactjsgoogle-cloud-platformdjango-rest-frameworkcorsgoogle-api-gateway

My React Google Cloud Run app requests to Google API Gateway are blocked by CORS policy. What am I missing?


I have a React create-app App running on Google Cloud Run. On the backend, I've created a Google Cloud Run Django app, and served its API via API Gateway. I'm using Auth0 to authenticate requests.

On the react side, I've set my proxy in package.json as:

"proxy": "http://{api gateway url}",

While trying locally, whenever the app runs an axios request, I get the following error:

Access to XMLHttpRequest at 'https://{api gateway url}/api/users/' (redirected from 'http://localhost:3000/api/users/') from origin 'http://localhost:3000' 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.

In production though, my axios requests aren't re-directed to the proxy and for now all I'm getting are 405 errors.

I've checked that the url is correct and my axios requests has the following headers:

headers: AxiosHeaders
  Accept: "application/json, text/plain, */*"
  Access-Control-Allow-Headers: "Origin, X-Requested-With, Content-Type, Accept, Authorization"
  Access-Control-Allow-Methods: "DELETE, GET, OPTIONS, PATCH, POST, PUT"
  Access-Control-Allow-Origin: "*"
  Authorization: "Bearer {token}"
  Content-Type: "application/json"

and in production I've added proxy to my axios requests but this doesn't seem to work.

I've tried enabling CORS both in API gateway config:

host: "{api gateway url}"
x-google-endpoints:
- name: "{api gateway url}"
  allowCors: True

and in my Django settings.py as well:

CORS_ALLOW_CREDENTIALS = True

CORS_ALLOW_METHODS = [
    "DELETE",
    "GET",
    "OPTIONS",
    "PATCH",
    "POST",
    "PUT",
]

CORS_ALLOW_HEADERS = [
    "accept",
    "accept-encoding",
    "authorization",
    "content-type",
    "dnt",
    "origin",
    "user-agent",
    "x-csrftoken",
    "x-requested-with",
]

CORS_ALLOW_ALL_ORIGINS = True

INSTALLED_APPS = [
    ...
    'corsheaders',
    ...
]

MIDDLEWARE = [
    ...
    'corsheaders.middleware.CorsMiddleware',
    ...
]

What am I missing? And how can I make sure my requests in prod are being routed correctly? Would appreciate any lead on this 🙏 !


Solution

  • As per this google groups discussion, Seems currently CORS configuration for API Gateway is not supported. As a workaround you can try using ESPv2 running on Cloud Run.

    You can also check this answer by @Cloudkollektiv. And there exists a feature request for the same in issue tracker, you can either add your concern there or create a new issue here