Cross Origin Resource Sharing (CORS) is a security model where in general we are not allowed to access resources on a server from another server.
For example if we have a Single Page Application (React/Angular etc) running on widget.com, this application has no server side code. Then in a different location we have our API, it could be an Express server or Amazon API Gateway, it doesn’t matter, it is a resource that is in a different location.
A very common use case is for the single page application to request data from the API. By default this is prohibited (by the browser), because of the CORS security model.
So how do we configure our API and SPA so that they are allowed to communicate with each other? The API server needs to send the correct headers telling the browser that this cross-site access is ok.
Anytime you make a CORS HTTP request, the browser will send a pre-flight request, which is another smaller HTTP request in order to make sure that the API (or whatever other resource) will grant the original request.
The pre-flight isn’t the request itself. Instead, it contains metadata about it, such as which HTTP method is used and if the client added additional request headers. The server inspects this metadata to decide whether the browser is allowed to send the request.
For example if we send a POST request to our API, the pre-flight checks to make sure that there is even a POST method available on that endpoint!
Therefore when we are configuring an API we need to be prepared to handle these pre-flight requests.
Pre-flight requests are sent with the HTTP OPTIONS method. And therefore we need to provide an OPTIONS endpoint on each of our routes if we want them to be able to accept CORS traffic.
If we are using API Gateway this process is simple for us, we can simply check the Enable API Gateway CORS option when we are creating resources in our API.
And then we can see that OPTIONS is already available under the methods for this resource
Furthermore we can see that in our Integration Response we have a list of acceptable headers.
That is all that is required on AWS API Gateway to configure the API to accept all of these CORS requests.