Search code examples
amazon-web-servicesaws-lambdaaws-api-gatewayaws-serverless

Enable CORS in AWS API Gateway with aws-cli


I'm currently writing script to programmatically enable CORS once a resource is added to an API Endpoint on AWS API Gateway. After exploring the put-integration-response function for hours. I almost got a breakthrough, but here is an error I'm getting:

An error occurred (BadRequestException) when calling the 
PutIntegrationResponse operation: Invalid mapping expression specified: 
Validation Result: warnings : [], errors : [No method response exists 
for method.]

Here is the script I'm using to enable CORS:

aws apigateway put-integration-response --rest-api-id XXXXX --resource 
-id XXXX --http-method GET --status-code 200 --selection-pattern 200 -- 
response-parameters '{"method.reponse.header.Access-Control-Allow- 
Origin": "'"'*'"'", "method.response.header.Access-Control-Allow- 
Headers": "'"'integration.request.header.Authorization'"'"}'

The weird thing I found was the AWS documentation seems to be out of date with the current version of the aws-cli It tooks me hours to fix some basic issues I had with the api call.

Will be grateful for any ideas.

Cheers! Nyah


Solution

  • Couple of issues found in your AWS CLI command for aws apigateway put-integration-response

    1. There is a typo mistake

    method.reponse.header.Access-Control-Allow-Origin

    It must be:

       method.response.header.Access-Control-Allow-Origin
    
    1. To set a value '*' to Access-Control-Allow-Origin you need to use "'"'"'*'"'"'" instead of "'"'*'"'" In response-parameters you can set method.reponse.header.Access-Control-Allow-Origin, but can not set method.response.header.Access-Control-Allow-Headers
    2. The reason of the error

    PutIntegrationResponse operation: Invalid mapping expression specified

    is because you are trying to set method.response.header.Access-Control-Allow-Headers in response-parameters

    Below should be the final AWS CLI command

    aws apigateway put-integration-response --rest-api-id XXXXX --resource-id XXXX --http-method GET --status-code 200 --selection-pattern 200 
    --response-parameters '{"method.response.header.Access-Control-Allow-Origin": "'"'"'*'"'"'"}'