Setting up CORS on Amazon API Gateway

๐Ÿ“˜

Informational only

This page is unofficial and unsupported. Consult the Amazon API Gateway documentation for more information.

๐Ÿ“˜

Amazon API Gateway tips

  • Remember to deploy your API after making changes in Amazon API Gateway.
  • CORS error messages are only displayed in the browser's console. Make sure to check there for error messages.

This example shows one way of configuring CORS for an API hosted on Amazon API Gateway. This example uses the Amazon Management Console for an AWS REST API and uses a MOCK Integration Request for any OPTIONS requests made to the API. Additionally, the actual endpoint method (for example, GET) must be configured to return the Access-Control-Allow-Origin method.

Configure the OPTIONS method

To configure the OPTIONS method, start by creating a generic proxy resource /{proxy+} with an OPTIONS method. This generic proxy resource will be used to handle OPTIONS requests for all resources (other than the root resource) of your API. This avoids the need to set up CORS for each resource in your API.

2610

This will create a /{proxy} resource for your API. Because you selected Enable API Gateway CORS above, an OPTIONS method will be created for you. Delete the ANY method. The OPTIONS method uses the MOCK Integration Request type, as shown below.

2568

Click on Method Response (see above) to configure the allowed response headers. Expand the 200 status and click Add Header and include headers as described here (see below).

1978

Click on Integration Response (see above) to configure the actual CORS headers for your API. Expand Header Mappings and set the values for the headers as described here (see below).

2124

Configuring the actual endpoint method

The response to your actual endpoint method must include the Access-Control-Allow-Origin response header with the value set to your Enterprise Hub URL. You can include this header in your Lambda function:

exports.lambdaHandler = async (event, context) => {
    try {
        // const ret = await axios(url);
        response = {
            'statusCode': 200,
                    headers: {
            "Access-Control-Allow-Origin": "https://rapidapi-training.hub.rapidapi.com"
        },
            'body': JSON.stringify({
                message: 'hello world',
            })
        }
    } catch (err) {
        console.log(err);
        return err;
    }

    return response
};

Alternatively, you can return this header from Amazon API Gateway itself. In your method's Integration Request, make sure Use Lambda Proxy Integration is not checked:

2236

In your method's Method Response, add the Access-Control-Allow-Origin response header:

2296

In your method's Integration Response, set the value of the Access-Control-Allow-Origin response header to your Enterprise Hub's URL:

2424

Your API should now successfully be testable from the API Hub, with no CORS issues.