CORS chaos, or to CORS or not to CORS
Setting up CORS can be a hassle. If you deploy your endpoint to the same domain as your frontend, you can just skip it.
Adding a rewrite to firebase.json allows you to call your endpoint on the same domain. But how do you get that working locally during development?
proxy.conf.json
.Anyone who claims to never have been confused by CORS is either a genius or has selective memory. Adding to the confusion is the fact that CORS errors are also shown in the browser when the source of the error is something completely different, like the function crashed.
One way to not have to deal with CORS is to have your endpoints on the same domain as your webpage. In the case of firebase this is done by rewrites in firebase.json
. You specify the path and which function should be called for it:{"source": "/my-path/**", "function": "myFunc"}
. Now you will be able to call your function without worrying about CORS. If you have an SPA, you will have another rewrite to serve your application for all URLs. Make sure the rewrite for your function is before that one.
So far so good, but to be able to call your function when running the functions emulator more setup is needed. The reason for that is that you are calling a relative link now, like localhost:4200/
my-path
and this will be caught by the same server that serves your angular application. So again, adding a rewrite is necessary this time to tell webpack to redirect the call to the backend. So the call is proxied from localhost:4200/
my-path
to say localhost:5001/
my-path
. This is done by adding by adding "proxyConfig": "src/proxy.conf.json"
to yourproject.architect.serve.options
in angular.json
.
Update: using localhost worked with node v16, but not with node v18! Webpack-dev-server will throw [ECONNREFUSED]. The error has something to do with the dev-server preferring ipv6. It is easily solved by using 127.0.0.1 instead of localhost when proxying.