api gateway CORS setup

2019-07-18 22:03发布

问题:

I'm attempting to setup aws CORS from the command line using aws-cli in a deployment script. I have created the POST Resource with the following perl to shell command. I'm attempting to set the integration-response to '*' much like enabling cores would do.

aws apigateway put-method-response \\ --region "$region" \\ --rest-api-id "$api_id" \\ --resource-id "$resource_id" \\ --http-method "POST" \\ --status-code 200 \\ --response-models '{"application/json":"Empty"}' \\ --response-parameters '{"method.response.header.Access-Control-Allow-Origin":true}'

When i run the following command to set the integration value.

aws apigateway put-integration-response \\ --region "$region" \\ --rest-api-id "$api_id" \\ --resource-id "$resource_id" \\ --http-method "$method" \\ --status-code 200 \\ --response-template '{"application/json":"Empty"}' \\ --response-parameters \\ '{"method.response.header.Access-Control-Allow-Origin": "'*'"}'

I get the following error.

A client error (BadRequestException) occurred when calling the PutIntegrationResponse operation: Invalid mapping expression specified: Validation Result: warnings : [], errors : [Invalid mapping expression specified: *]

Can anyone tell me what this error is really referring to or even a better way to go about a api gateway deployment script.

回答1:

The API Gateway management console has a nice 'Enable CORS' feature, which you may have seen. As far as replicating using the CLI, I'd suggest using the console feature, observing the configuration afterwards, and using the same parameters in the CLI requests.

The error you're seeing must be caused by incorrect escaping of the single quotes for the value '*' because just the character * would not be valid. Also just to point out another potential problem, the input to --response-templates '{"application/json":"Empty"}' is valid but is not interpreted the same as --response-models in a method-response object. That value will set the response body to "Empty" for all API calls that use that integration-response. To do a passthrough, just don't set the value of --response-templates



回答2:

The issue did end up being the correct way to escape the characters.

--response-parameters '{"method.response.header.Access-Control-Allow-Origin":"'"'*'"'"}'

Apparently this was more about knowing the correct way to format the JSON.