天天看点

AWS API Gateway和Lambda的简单测试具体流程创建Lambda应用创建API GatewayS3 Bucket网页测试触发API Gateway和Lambda函数碰到S3 Bucket删除问题术语Reference

文章目录

  • 具体流程
  • 创建Lambda应用
  • 创建API Gateway
  • S3 Bucket网页测试触发API Gateway和Lambda函数
  • 碰到S3 Bucket删除问题
  • 术语
  • Reference

测试了一下使用API Gateway来触发Lambda应用,并将结果显示在网页上。

Lambda支持语言为: Node.js,Java,Python,C#,Go,PowerShell,等等。它具有无需管理服务器,根据需求自动扩展,便宜等优势。

具体流程

在S3 Bucket里存放网页,显示网页后,在网页里通过API Gateway来触发Lambda功能应用,并将Lambda功能应用返回的结果显示在网页上。Route53来使用DNS网址为可选。

创建Lambda应用

Lambda是EC2在一起的Compute界面下,点进去后,再点

Create Function

来创建函数, 取名为:

XiongLambdaFunction

,语言设置为Python 3.6,这样会自动生成以下代码:

import json

def lambda_handler(event, context):
    # TODO implement
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }

           

进行以下替换:

import json
def lambda_handler(event, context):
    print("In lambda handler")

    resp = {
        "statusCode": 200,
        "headers": {
            "Access-Control-Allow-Origin": "*",
        },
        "body": "Xiong Huilin"
    }

    return resp
           

创建API Gateway

创建一个API Gateway,在

Networking & Content Delivery

下点

API Gateway

,选择

REST

,API取名为:

XiongTestAPI

,在

Actions

下点

Create Method

,选择

GET

方法,Integration type选择

Lambda Function

,并选择前面已经创建的

XiongLambdaFunction

。点保存,有以下提示。

You are about to give API Gateway permission to invoke your Lambda function:

arn:aws:lambda:ap-southeast-1:606255748358:function:XiongLambdaFunction

Deploy API

对API进行发布,发布成功后会有一个URL生成,这个生成的URL将会被用做第三步测试:

Invoke URL: https://p9ciqi7imh.execute-api.ap-southeast-1.amazonaws.com/XiongReturnNameAPI

S3 Bucket网页测试触发API Gateway和Lambda函数

创建两个文件:Index.html和error.html,此测试是根据ACloud Guru所做的示例。

在index.html里,将GET请求的URL替换为: https://p9ciqi7imh.execute-api.ap-southeast-1.amazonaws.com/XiongReturnNameAPI,如下html代码所示:

<html>
<script>

function myFunction() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
        document.getElementById("my-demo").innerHTML = this.responseText;
        }
    };
    xhttp.open("GET", "https://p9ciqi7imh.execute-api.ap-southeast-1.amazonaws.com/XiongReturnNameAPI", true);
    xhttp.send();

}

</script>
<body><div align="center"><br><br><br><br>
<h1>Hello <span id="my-demo">2nd December 2019!</span></h1>
<button onclick="myFunction()">Click me</button><br>
<img src="https://www.dropbox.com/s/2965glxbyqjmi9h/SanTi.jpg?raw=1"></div>
</body>
</html>
           

error.html

<html><body><h1>There has been an error for Xiong's website!</h1></body></html>
           

创建一个S3 Bucket,取名为:

xionglambdatest

,在

Properties

下面进行设置,

Static website hosting

,创建了以下Endpoint,

Index document

设置为

index.html

Error Document

设置为

error.html

,保存。

Static website hosting

Endpoint : http://xionglambdatest.s3-website-ap-southeast-1.amazonaws.com

将前面创建的

index.html

error.html

进行上传,

如果你注册了域名的话,可以使用Route53来设置 A Record来指向S3 Bucket的Endpoint达到域名访问的目的。

这里直接测试:

Static website hosting

Endpoint : http://xionglambdatest.s3-website-ap-southeast-1.amazonaws.com

返回以下错误:

403 Forbidden
Code: AccessDenied
Message: Access Denied
RequestId: 0264A5A5BC4FBDE3
HostId: r03Yr+l5vDDiR/0YQL8if2qmRP1lBvBzLoeoGgw6z3jec8XnyWJsz790UwmZGI49ejY5QFYWrfE=
An Error Occurred While Attempting to Retrieve a Custom Error Document
Code: AccessDenied
Message: Access Denied
           

在S3 Bucket

xionglambdatest

中,设置

Make Public

,确认,再试,可以成功访问。

点按钮无反应,在Chrome的Develop Tool里发现碰到以下错误:

Access to XMLHttpRequest at 
'https://byaaiuzpad.execute-api.ap-southeast-1.amazonaws.com/XiongReturnNameAPI' 
from origin 'http://xionglambdatest.s3-website-ap-southeast-1.amazonaws.com' 
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is 
present on the requested resource.
           

CORS在作怪,在

Resource

下里的

Action

里点

Enable CORS

,再试, 点按钮后,界面返回如下:

Hello {"statusCode": 200, "headers": {"Access-Control-Allow-Origin": "*"}, 
"body": "Xiong Huilin"}
           

说明

https://p9ciqi7imh.execute-api.ap-southeast-1.amazonaws.com/XiongReturnNameAPI

返回了

{"statusCode": 200, "headers": {"Access-Control-Allow-Origin": "*"}, "body": "Xiong Huilin"}

重新再试,在创建

GET

方法时,记得把

Use Lambda Proxy integration

选择项选上, 表明是Lambda返回值 。另外记得在

Resource

下里的

Action

里点

Enable CORS

, 最后

Deploy API

。这次成功。

点按钮后,以下文字:

Hello 2nd December 2019!

变为:

Hello Xiong Huilin

也就是

https://p9ciqi7imh.execute-api.ap-southeast-1.amazonaws.com/XiongReturnNameAPI

返回了

Xiong Huilin

,测试成功!

点完按钮的效果如下:

AWS API Gateway和Lambda的简单测试具体流程创建Lambda应用创建API GatewayS3 Bucket网页测试触发API Gateway和Lambda函数碰到S3 Bucket删除问题术语Reference

碰到S3 Bucket删除问题

前面做Elastic Beanstalk测试的时候:AWS的CloudFormation和Elastic Beanstalk的简单测试,自动创建了名为

elasticbeanstalk-ap-southeast-1-606255748358

的S3 Bucket,删除时返回了

Access Denied

的错误。

参见: AWS Forum: can’t delete empty elasticbeanstalk created bucket

在以下Bucket Policy的JSON文件里将

Deny

改成

Allow

,就可以删除了,问题解决。

{
            "Sid": "eb-58950a8c-feb6-11e2-89e0-0800277d041b",
            "Effect": "Allow",
            "Principal": {
                "AWS": "*"
            },
            "Action": "s3:DeleteBucket",
            "Resource": "arn:aws:s3:::elasticbeanstalk-ap-southeast-1-606255748358"
        }
           

参见Bucket Policy Examples,可以使用以下JSON文件设置

Bucket Policy

以达到Bucket为公共访问的目的:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PublicRead",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::xionglambdatest/*"
        }
    ]
}
           

术语

Lambda:参见什么是 AWS Lambda?

REST:参见Representational_state_transfer 维基

Reference

Lambda Troubleshooting - Acloudguru

什么是 AWS Lambda?

Representational_state_transfer 维基

AWS的CloudFormation和Elastic Beanstalk的简单测试

AWS Forum: can’t delete empty elasticbeanstalk created bucket

ACloud Guru

Bucket Policy Examples

继续阅读