Last active
August 7, 2017 23:13
-
-
Save imalchenko/4bf160da778400c7583cf6f3aae268e9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
console.log('Loading function'); | |
exports.handler = (event, context, callback) => { | |
console.log('Received event:', JSON.stringify(event, null, 2)); | |
/* | |
See what our origin(what domain is making the request) | |
*/ | |
//console.log("Origin: " + event.headers.origin); | |
/* | |
Open up CORS for two specific domains - a CloudFront URL, and an S3 Storage bucket | |
This will let the CORS requests go through at the Lambda level and return results | |
*/ | |
let origin; | |
if(event.headers.origin == 'INPUT YOUR CLOUDFRONT URL' | |
|| event.headers.origin == 'INPUT YOUR S3 BUCKET URL') | |
{ | |
origin = event.headers.origin | |
} | |
/* | |
This will send out the response with either a 400 error or a 200 success | |
Note, also, the headers. We're making sure to pass application/json and allow CORS domain with a varible 'origin' | |
that we've defined above | |
*/ | |
const done = (err, res) => callback(null, { | |
statusCode: err ? '400' : '200', | |
body: err ? err.message : JSON.stringify(res), | |
headers: { | |
'Content-Type': 'application/json', | |
'Access-Control-Allow-Origin': origin, | |
}, | |
}); | |
/* | |
If we see an http requst, and it is a GET request, we'll return a simple JSON array. If not, we'll throw an | |
"unsupported method" and return it as a 400 error | |
*/ | |
switch (event.httpMethod) { | |
case 'GET': | |
done(null, {"messages": [{"id":1,"content":"Hello"},{"id":2,"content":"Serverless"},{"id":3,"content":"AWS"}]}); | |
break; | |
default: | |
done(new Error(`Unsupported method "${event.httpMethod}"`)); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample AWS Lambda function for a serverless app implementation(Written in Node.JS 6.10)
Article