React.js API calls to AWS Lambda, API Gateway and dealing with CORS

How to resolve a very frustrating CORS issue with AWS Lambda

Michael Whittle
codeburst
Published in
8 min readSep 16, 2020

If you have ever attempted to make an API call to API Gateway from a browser based web application you would have experienced the heartache of dealing with CORS.

You will probably have noticed that API calls using an API testing tool like Postman works without issue. The minute you try and make a call to the same API via a web based application it will fail because of CORS.

If you are not familiar with CORS this is the definition from Mozilla:

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own.

This basically means that “out the box” the FQDN where the API is hosted will block requests to the API that are not sourced from the same FQDN. So if your app is making a request from domain-a.com to an API served from domain-a.com it will work. If your app is making a request from domain-a.com to an API served from domain-b.com it will fail because of CORS. And this will be the case you will have with AWS API Gateway. The requests from your app will not be within the same domain as where the API Gateway is served. Now you would think this is an easy issue to fix but it isn’t and there is very little documentation on how to get this working. I have figured it out and wanted to share it with you.

The first step is to log into the Amazon AWS Console and search for Lambda under Find Services.

Click on the orange “Create function” button.

For the purpose of this tutorial you will want to select the default “Author from scratch”, give your function a name (in this case “mediumtutorial”, select the Runtime (in this case “Node.js 12.x”), and for the Execution role make sure you…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Written by Michael Whittle

Solution Architect — CCIE R&S #24223 | Full-Stack / Blockchain / Web3 Developer | Security Specialist | PyCryptoBot Creator

Responses (15)

Write a response

Thanks Michael. It is working as you explained. But AWS should do something about this otherwise it is painful. You are really expert in AWS.

--

Thanks for this Michael, I spent the last 3 hours trying to figure out why my CORS wasn't enabled after you know "Hitting enable for CORS".

--

how is this so unbelievably complex?? what is AWS doing ...

--