Step by step guide to show a html file from s3 bucket using lambda and API gateway
Part I: Uploading html file to S3 Bucket
1. Login and search in aws console S3
2. Create new bucket. Let name it: tech-shop
3. Upload registration.html (all other files, if any) in this bucket
Part II: Viewing html file
1. Create a lambda function. Let name it: userRegistration
2. Delete the default js code in lambda function in index.js
3. Write the following code in lambda function index.js file
<code start>
const aws = require('aws-sdk');
// set region
aws.config.region = 'ap-northeast-1';
// new S3 Object
const s3 = new aws.S3();
const params_to_get = {
Bucket: 'tech-shop',//process.env.BUCKET,
Key: 'registration.html'
};
/**
* Get login file from S3.
*/
exports.handler = async (event) => {
try {
const data = await s3.getObject(params_to_get).promise();
return data.Body.toString();
} catch (e) {
return {
statusCode: 500,
body: JSON.stringify(e.message),
};
}
};
4. Create test event in lambda function. Let name it testevent and click on Test to test it
5. Create resource in API gateway to access the lambda function. Let name it user-registration
6. Create get method in user-registration resource
7. Go to method response add two headers: Access-Control-Allow-Origin and Content-Type
8. Go to integration response add mapping template, set values '*' for Access-Control-Allow-Origin and 'text/html' for Content-Type and write in text area $input.path('$') on template part of the text/html
9. Click on actions, then Deploy API and choose stage if you want to deploy any of existing stages or create new stage. Let name it: web
10. After deploy you will get the link and add stage name/resource name to check the response. Example:
https://37i140nmj9.execute-api.ap-northeast-1.amazonaws.com/[stage-name]/[resource-name]
https://37i140nmj9.execute-api.ap-northeast-1.amazonaws.com/web/user-registration
Comments
Post a Comment