"Enable CORS" in AWS API Gateway resource?

Viewed 1421

I have a problem with AWS API Gateway. I'm developing a web application with Angular 4 (using TypeScript language), but if I invoke the PUT method from the frontend, the following error message appears:

Method PUT is not allowed by Access-Control-Allow-Methods in preflight response.

and it's very strange because in the AWS console the PUT method works perfectly (I did many tests directly from the API Gateway console with a stage after the deploy, and everything works well). If I go to "Actions/Enable CORS" all methods have the check, included the PUT method, and I don't explain exactly what is the problem with the API Gateway.

Why do I get this error if it seems all ok in API gateway? Is there a way to change these CORS?

3 Answers

What I recall when being smacked by this same problem a while ago...

When using a Lambda or HTTP proxy integration, you need to specify at a minimum the Access-Control-Allow-Origin header the in your lambda's response. You may have specify additional (don't have any code handy at the moment). I do recall this message to be somewhat misleading, and that testing from the management console works because it's not really using CORS because of how the console executes the tests.

Have a look at the last section in: Enabling CORS for a REST API resource

exports.handler = async (event) => {
    const response = {
        statusCode: 200,
        headers: {
            "Access-Control-Allow-Headers" : "Content-Type",
            "Access-Control-Allow-Origin": "https://www.example.com",
            "Access-Control-Allow-Methods": "OPTIONS,POST,GET"
        },
        body: JSON.stringify('Hello from Lambda!'),
    };
    return response;
};

You need to replace Access-Control-Allow-Origin with the host name used by your client app. As a quick test use *, but don't go to production as that defeats the purpose of CORS.

Try to add your authorizer's Token Source to the AllowHeaders.

Click on Enable CORS, then add the Token Source to the end of Access-Control-Allow-Headers

AllowHeaders: "'Content-Type, Authorization, X-Amz-Date, X-Api-Key, X-Amz-Security-Token, {your Token Source}'"

enter image description here

Related