#Cors with #AWS Serverless #Lambda
One of the key elements of serverless computing, is that you probably end up making requests to a third party domain via ajax to do any dynamic processing. In this case I’m imagining you are calling a Lambda function on AWS from a static website hosted on S3.
But, unless you enable CORS (Cross origin resource sharing) then the browser will prevent this type of AJAX calls being made.
So, you will need to do two things to enable CORS on AWS. The first, it log into API gateway, and select Enable CORS on the Actions drop down.
However, this is only half of the battle, since it enables CORS on the OPTIONS preflight request, you need to also set the CORS header in your lamda function, for which I use the following helper function;
function cors(data)
{
var response = {
statusCode: 200,
headers: {
‘Access-Control-Allow-Origin’: ‘*’,
‘Access-Control-Allow-Credentials’: true,
},
body: JSON.stringify(data),
};
return response;
}
Then, whenever you are returning from your lambda, you write something akin to;
callback(null, cors(“Hello World”));