0
votes

I built a simple RESTful endpoint using AWS Lambda and API gateway. API Gateway has CORS enabled, and the client is sending the proper headers as described here

The client app was built in Django and uses JQuery:

 $.ajax({
    type: 'GET',
    url: baseUrl,
    crossDomain: true,
    contentType: 'application/json'
})

Also, the Lambda function itself returns the following payload:

return {
    'statusCode': 200,
    'headers': {
        'Content-Type': 'application/json',
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Credentials": "true"
    },
    'body': json.dumps(json_response)
}

Chrome is still throwing a CORS error:

No 'Access-Control-Allow-Origin' header is present on the requested resource

Am I missing something?

2
Most browsers will send a "preflight" OPTIONS request to the endpoint, if this response contains the correct CORS headers will then send the actual request. You need to configure your endpoint to send the correct CORS headers for OPTIONS requests docs.aws.amazon.com/apigateway/latest/developerguide/…Iain Shelvington
Thanks! The OPTIONS method is already returning proper CORS headers though: Access-Control-Allow-Headers, Access-Control-Allow-Methods and Access-Control-Allow-Originvt_todd
What’s the HTTP status code of the response? You can use the Network pane in browser devtools to check. Is it a 4xx or 5xx error rather than a 200 OK success response?sideshowbarker
Try doing "Enable CORS" from Actions menu. It'll add an OPTIONS method. Post doing this, follow the following link. Hope it helps. stackoverflow.com/questions/35190615/…Showmik Bose

2 Answers

0
votes

I couldn't tell if your question was answered based on the comments, but you may be missing the "Access-Control-Allow-Headers" header.

{
    "headers" : {
        'Access-Control-Allow-Origin' : '*',
        'Access-Control-Allow-Headers':'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token',
        'Access-Control-Allow-Credentials' : True,
        'Content-Type': 'application/json'                        
    },
    "isBase64Encoded": False,
    "statusCode": 200,
    "body"  : json.dumps(json_response),
}

For this to work, you have to be using LAMBDA_PROXY integration on the API Gateway endpoint.

0
votes

Found the answer here

Under Gateway Responses, edit the Default 4xx settings and add the Response Header 'Access-Control-Allow-Origin' : '*'

Note: once I did that I got a { "message" : "forbidden" } response from the API, I needed to add headers to the API call in JQuery:

 $.ajax({
    type: 'GET',
    url: baseUrl,
    crossDomain: true,
    headers: { "x-api-key": apiKey },
    contentType: 'application/json'
})