Home > Back-end >  Manage CORS between Google App Engine & Google Cloud Function
Manage CORS between Google App Engine & Google Cloud Function

Time:09-17

I'm trying to set up a new instance of a simple App Engine which communicate with a backend-function hosted on Google Cloud Function. The App Engine is protected with IAP, and the Google Cloud Function is private only. The GAE use Angular Framework and GCF use Node 14 with Express .

I can't access to my GCF from the App Engine because the requests are blocked by CORS.
Access to XMLHttpRequest at '' from origin '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I tried the popular solutions on the web :

  1. Use the cors librairie on the GCF. So I had on my GCF
var cors = require('cors')
app.use(cors(cors({ credentials: true, origin: true })))

And I also add this line for every request

res.set('Access-Control-Allow-Origin', '*')
  1. Add the http-header on my app.yaml
handlers:
  - url: /(.*\.[A-Za-z0-9]{1,4})$
    static_files: dist/\1
    upload: dist/(.*\.[A-Za-z0-9]{1,4})$
    http_headers: 
      Access-Control-Allow-Origin: "*"
  - url: /(.*)$
    static_files: dist/index.html
    upload: dist/index.html
    http_headers: 
      Access-Control-Allow-Origin: "*"

But I still get the same error message.

EDIT : so the first problem was due to an authentication issue, that why the error have the same response. So I decided to deploy the 2 apps on App Engine to simplify communication between the 2 services.

CodePudding user response:

  • You can now have full access to the HTTP Request/Responses by setting the appropriate CORS headers as per this documentation.
  • Just so you know the reason for the error you are facing, it is because when your web browser is calling a service that is in a different/cross domain, it doesn’t make a HTTP request right away, it rather starts with making an OPTIONS request( a preflight request) and compares the value of Access-Control-Allow-Origin header in the result with the current domain i.e. it checks for this (req.method === 'OPTIONS') in the headers and if the header value matches the host, the actual call is made, otherwise the action is stopped and the error as the one above is thrown.
  • To have a thorough understanding of the above concept, have a look at this stackoverflow answer and read this article for more insights.
  • Related