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.

Image for post

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 select “Create a new rule with basic Lambda permissions”. If this isn’t your first Lambda function you may want to “Use an existing role”.

Image for post

It will take some time to create the function but once completed you will be on the Configuration screen. There are many useful options there but for the purpose of the tutorial I want to keep this as simple as possible. Please scroll down to the “Function code” section to find the default “Hello from Lambda!” code.

Image for post

#cors #react #api-gateway #aws #lambda

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