简体   繁体   中英

CORS error calling AWS API Gateway from Django

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?

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.

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'
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM