"no 'access-control-allow-origin' header is present on the requested resource" when contacting AWS REST API

Viewed 51

This isn't a question, but a Solution. I struggled with a bug for a few days and was constantly looking in the wrong spot since I couldn't find anything online about it. So I decided to post it for anyone else having the same issue.

I have been trying to call an AWS API, which would call an AWS Lambda function (basically, back end code for those who aren't familiar). However, I kept running into an issue were an error stating

Access to XMLHttpRequest at [API URL] from origin [Website URL] has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

would pop up in the console of the website I was calling the API from.

I had enabled CORS in the Amazon API, so it shouldn't have caused an issue.

After a few days, I found out that the issue wasn't the API, but it was in the lambda function itself.

The issue stems from the response the lambda function would return. Although not always necessary, lambda functions are sometimes required to return a HTTP response if they are communicating to an API(such as in my case). But, since my response did not have any headers, it caused an issue. I was returning the following response:

response = {
  "statusCode": 200,
  "body": "",
  "isBase64Encoded": false
};

Furthermore, since the API was set up to use the Lambda Proxy Integration, the communication worked as if the lambda function sent a response directly to the website instead of sending it through the API who had the CORS methods set.

So, to remedy this, I mortified the code as follows:

response = {
  "statusCode": 200,
  "headers": {
     "Access-Control-Allow-Origin": "*",
   },
   "body": "",
    "isBase64Encoded": false
};
0 Answers
Related