AWS API Gateway - CORS + POST not working

前端 未结 9 1745
一生所求
一生所求 2020-12-01 10:34

CORS is really driving me crazy and I\'m really out of ideas as of what to try to make it work.

I have created a simple APIG Api with 1 resource cal

相关标签:
9条回答
  • 2020-12-01 10:59

    Ok, I found the origin of the problem, which happens to be totally unrelated to APIG, and confirms what @AbhignaNagaraja mentioned, that my APIG was properly configured.

    The issue is actually in the way I called jQuery.ajax, which I thought was smart enough to convert my parameters to a JSON string when contentType is 'application/json'. It seems I had to manually stringify the JSON params rather than passing a JSON and having jQuery stringify it.

    So this is the bad call:

    $.ajax({
            url: myEndpoint,
            type: 'POST',
            crossDomain: true,
            data: {
                url: $('#url').val()
            },
            headers: {
                "X-Api-Key": 'blablabla'
            },
            dataType: 'json',
            contentType: "application/json",
            success: function (data) {
                console.info(data);
            }
        });
    

    And this is the right call:

     $.ajax({
            url: myEndpoint,
            type: 'POST',
            crossDomain: true,
            data: JSON.stringify({
                url: $('#url').val()
            }),
            headers: {
                "X-Api-Key": 'blablabla'
            },
            dataType: 'json',
            contentType: "application/json",
            success: function (data) {
                console.info(data);
            }
        });
    

    This can be a hint if you are debugging such an issue with CORS: just download the AWS APIG SDK and try executing the call using the apigClient provided by AWS and compare headers with the ones you get with your custom client. When examining the 2 sets of headers I got with jQuery and apigClient, I noticed the Request Payload looked different and thats how I realized the format was wrong, then the 400 code and the No 'Access-Control-Allow-Origin' header is present all made sense.

    I hope this helps.

    0 讨论(0)
  • 2020-12-01 11:02

    There have been many posts that direct you to make sure the lambda function is returning the appropriate CORS headers, and they are correct. However, it is also critical that the json object is stringified using JSON.stringify(). It seems that Postman does this for us, so it is misleading when the Postman request and the $.ajax request send the same json object; yet one succeeds and one fails.

    0 讨论(0)
  • 2020-12-01 11:04

    Here in 2020 and still finding other causes of the API Gateway CORS issues. For me (not using lambda proxy) I was still getting the CORS error even after using the API dropdown to enable CORS, and even after adding the 'Access-Control-Allow-Origin' header to the response from my Lambda function.

    What fixed it for me as adding the 'Access-Control-Allow-Origin' to the default Gateway Responses. Within the API Gateway UI, on the left-side menu, find Gateway Responses. Select 'Default 4XX' and edit it to include the 'Access-Control-Allow-Origin'. I set the value at '*' to be totally open during testing (including the quotes). Do the same for 'Default 5XX'. My ajax calls were able get passed the CORS error and now I see the real cause - the required parameters I set for the method weren't being passed in correctly.

    Yet, I don't know why did that present as a CORS error.

    0 讨论(0)
  • 2020-12-01 11:09

    I had a similar issue - and it had nothing to do with the way that the API was configured or the POST request that I was making on the front-end. What fixed the problem for me was deploying the API on AWS API Gateway. Once you create an API method/resource, and tie them to a lambda function, they do not auto deploy.

    You have to click "Actions" and then "Deploy API" in order to access these MicroServices from the front-end.

    0 讨论(0)
  • 2020-12-01 11:11

    If you are using proxy integration in API Gateway, then enabling CORS from API Gateway doesn't work. You have to set the Header 'Access-Control-Allow-Origin' from your Lambda code itself.

    Its mentioned in the doc.

    Python code sample:

        response = {
            'statusCode': 200,
            'headers': {
                'Access-Control-Allow-Origin': '*'
            },
            'body': json.dumps({'message': 'CORS enabled')
        }
        return response
    
    0 讨论(0)
  • 2020-12-01 11:13

    to resolve this i present to you my config of the Post configuration in apy gateway

    Option method - Integration REsponse - Headers Mapping

    X-Requested-With '*'
    Access-Control-Allow-Headers 'Content-Type,x-requested-with,Access-Control-Allow-Origin,Access-Control-Allow-Headers,Access-Control-Allow-Methods'
    Access-Control-Allow-Origin 'http://localhost:4200'
    Access-Control-Allow-Methods 'POST,OPTIONS'
    

    Post Method - Integration Response - Headers Mapping

    Access-Control-Allow-Origin "*" ---> can be changed by your ip obviously
    

    I hope this helps you

    0 讨论(0)
提交回复
热议问题