[Troubleshooting] CORS setting was not working when I implemented AWS API Gateway+Lambda Server-less Application
This is record of troubleshooting about CORS setting when I implemented AWS server-less application
It’s a common things using combination of Lambda and API Gateway. If you already know that two services, it’s very simple to implement server-less environment. But if you not, it needs time to search about that, so I decided to record my troubleshooting history.
Simple & Non-simple Request
Do you guys know that cross-origin request is divided 「Simple cross-origin HTTP request」 and 「Non-simple cross-origin HTTP request」?
In the CORS(Cross Origin Resource Sharing) documents, there is explanation of what is simple request. And document said that non-simple requests are the others of simple request.
CORS enable setting is not working in non-simple request.
I said the answer first.
Enable CORS actions at Lambda proxy request is not working. Because Lambda proxy request is non-simple request.
We need to do another action.
If you enable CORS, and then send request to API Gateway…..
No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
You can see the error as shown above. If you have any experience of implementing RES API service, you might be familiar this error message.
How can I communicate under the cross origin environment?
I know, you don’t want the reason why error occurred. I start to solve this problem.
- Add Access-Control-Allow-Origin Header to your response code.
- Serialize your response body.
If you do this two things, you can do cross origin communication.
I write some code to help your understanding. This below code is basic Lambda code. I used Node.js 12.x version.
Actually I’m PHPer, but I cannot use PHP code to use Lambda. I heard I can use PHP for Lambda unofficially, but in this time, I use Node.js code.
It’s very fantastic things that we can create server-less service easily using API Gateway and Lambda.
I think you(and I) will stuck when you implement server-less service. But we already know our skills grew when we clear some problems. Let’s enjoy troubleshooting!