1
votes

I have a AWS Lambda function that is triggered via AWS API Gateway. When I test my function on Lambda it is working. When I send a POST request to the API url via ajax, I get a 502 bad gateway error.

XMLHttpRequest cannot load https://xxxxxxxx.execute-api.us-east-1.amazonaws.com/prod/myLambdaFunction. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'mywebsite.com' is therefore not allowed access. The response had HTTP status code 502.

Obviously this was a CORS issue, so I thought I could change the CORS settings in my AWS API Gateway URL which I did, but I am still getting an error for this.

What do I have to change on AWS side or my own to be able to POST to the URL?

2
did you deploy your API Gateway again after you changed the CORS settings?Dave Maple
There's a CORS error, but the real issue could be the 502 error. The CORS error seems like it could be a side effect of the 502, rather than the cause.Michael - sqlbot
yeah i think your right @Michael-sqlbot - can't figure out the reason for the 502. The logs don't give any indication of what is happening.luke

2 Answers

2
votes

Unfortunately there is a known issue with many classes of 4xx and 5xx errors where CORS headers will not be sent, even if you've added CORS support via the console.

As noted in comments, the CORS error is a side effect of the fact that your API is returning a 502. This often occurs if you are using the LAMBDA_PROXY integration type and are returning invalid JSON from your Lambda function.

Please try either using the test invoke functionality from the console or enable logging in your API to debug further.

0
votes

I solved that exact same problem by outputting the CORS header myself. See below - and I hope that'll help. Teebo

Amazon docs

function respond(context, responseData) {
var response = {
  statusCode: 200,
  body: JSON.stringify(responseData),
  headers: {
    "Content-Type": "application/json; charset=utf-8",
    "Access-Control-Allow-Origin": "*"
  }
};
context.succeed(response); }