[Cloud] 기본 웹 애플리케이션 구축하기

Sora·2022년 4월 3일
0

☁️ [Cloud]

목록 보기
5/6
post-thumbnail

☁️ 1. 웹, 앱 만들기

1.1 Amplify 콘솔을 사용하여 웹 앱 만들기

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Hello World</title>
</head>

<body>
    Hello World
</body

index.html에 위와 같은 코드를 작성해고 html.zip으로 압축해주었다.

앱 이름 : GettingStarted
환경이름 : dev
방법 : 드래그 앤 드롭
업로드 파일 : html.zip

1.2 웹 앱 테스트

도메인 클릭시 아래 사진 처럼 나온다.

☁️ 2. 서버리스 함수 작성

2.1 Lambda 함수 생성 및 구성

함수 이름 : HelloWorldFunction
런타임 : Python 3.8

2.2 Lambda 함수 테스트

☁️ 3. 서버리스 함수를 웹 앱에 연결

3.1 새 REST API 생성

3.2 새 리소스 및 메서드 생성

3.3 API 배포

3.4 API 검증

☁️ 4. 데이터테이블 생성

4.1 DynamoDB 생성

4.2 IAM 정책을 생성하여 Lambda 함수에 추가

4.3 DynamoDB 테이블에 데이터를 쓰도록 Lambda 함수 수정

# import the json utility package since we will be working with a JSON object
import json
# import the AWS SDK (for Python the package name is boto3)
import boto3
# import two packages to help us with dates and date formatting
from time import gmtime, strftime

# create a DynamoDB object using the AWS SDK
dynamodb = boto3.resource('dynamodb')
# use the DynamoDB object to select our table
table = dynamodb.Table('HelloWorldDatabase')
# store the current time in a human readable format in a variable
now = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())

# define the handler function that the Lambda service will use as an entry point
def lambda_handler(event, context):
# extract values from the event object we got from the Lambda service and store in a variable
    name = event['firstName'] +' '+ event['lastName']
# write name and time to the DynamoDB table using the object we instantiated and save response in a variable
    response = table.put_item(
        Item={
            'ID': name,
            'LatestGreetingTime':now
            })
# return a properly formatted JSON object
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda, ' + name)
    }

4.4 변경 사항 테스트

☁️ 5. 웹 앱에 상호 작용 기능 추가

5.1 Amplify 콘솔을 사용하여 웹 앱 업데이트

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Hello World</title>
    <!-- Add some CSS to change client UI -->
    <style>
    body {
        background-color: #232F3E;
        }
    label, button {
        color: #FF9900;
        font-family: Arial, Helvetica, sans-serif;
        font-size: 20px;
        margin-left: 40px;
        }
     input {
        color: #232F3E;
        font-family: Arial, Helvetica, sans-serif;
        font-size: 20px;
        margin-left: 20px;
        }
    </style>
    <script>
        // define the callAPI function that takes a first name and last name as parameters
        var callAPI = (firstName,lastName)=>{
            // instantiate a headers object
            var myHeaders = new Headers();
            // add content type header to object
            myHeaders.append("Content-Type", "application/json");
            // using built in JSON utility package turn object to string and store in a variable
            var raw = JSON.stringify({"firstName":firstName,"lastName":lastName});
            // create a JSON object with parameters for API call and store in a variable
            var requestOptions = {
                method: 'POST',
                headers: myHeaders,
                body: raw,
                redirect: 'follow'
            };
            // make API call with parameters and use promises to get response
            fetch("YOUR-API-INVOKE-URL", requestOptions)
            .then(response => response.text())
            .then(result => alert(JSON.parse(result).body))
            .catch(error => console.log('error', error));
        }
    </script>
</head>
<body>
    <form>
        <label>First Name :</label>
        <input type="text" id="fName">
        <label>Last Name :</label>
        <input type="text" id="lName">
        <!-- set button onClick method to call function we defined passing input values as parameters -->
        <button type="button" onclick="callAPI(document.getElementById('fName').value,document.getElementById('lName').value)">Call API</button>
    </form>
</body>
</html>

모듈 1에서 작성한 index.html을 위와 같이 수정한다. 그 후 zip파일로 재배포한다.

5.2 업데이트된 웹 앱 테스트


😢 오류 발생!

처음 실행했을 때 아래와 같은 오류가 발생하였다.

이는 람다 함수를 만들 때 리전을 필자가 임의로 서울로 변경했는데 이 때문에 해당 오류가 발생하였다.

수정 후에는 다음과 같이 잘 해결됨을 알 수 있다!

☁️ 참고자료

AWS 기본 웹 애플리케이션 구축

0개의 댓글