简体   繁体   English

需要从 JavaScript 调用 AWS Lambda 的示例

[英]Need example of calling AWS Lambda from JavaScript

Just need an example of how to call AWS Lambda from JavaScript running in a browser and display function result in JavaScript console.只需要一个示例,说明如何从在浏览器中运行的 JavaScript 调用 AWS Lambda,并在 JavaScript 控制台中显示 function 结果。 Incredibly, I cannot find any examples on Google or from AWS documentation.令人难以置信的是,我无法在 Google 或 AWS 文档中找到任何示例。

My use case is that I have an HTML form.我的用例是我有一个 HTML 表单。 When the form is submitted, I want to use Lambda to process the form inputs.提交表单时,我想使用 Lambda 来处理表单输入。 Assuming that the Lambda function finishes with no errors, I then want to take the user to a thank you page.假设 Lambda function 没有错误地完成,然后我想将用户带到一个感谢页面。

Please include a complete HTML example, not just a code snippet.请包括完整的 HTML 示例,而不仅仅是代码片段。

Since you need to run Lambda from the browser, you have two options you can achieve it. 由于您需要从浏览器运行Lambda ,因此您可以使用两个选项来实现它。

  1. Use AWS Javascript SDK , set it up with user via static configuration or Cognito with IAM Permissions to your Lambda . 使用AWS Javascript SDK ,通过静态配置向用户设置,或者通过IAM PermissionsCognito设置为Lambda You can also consider subscribing your Lambda functions to SNS Topic and run the Lambda by sending a message to the topic. 您还可以考虑将您的Lambda函数订阅到SNS Topic并通过向主题发送消息来运行Lambda This SNS approach would also require you to store and retrieve the submission state via separate call. 此SNS方法还需要您通过单独调用来存储和检索提交状态。

  2. Use AWS API Gateway to create RESTful endpoint with proper CORS configuration that you can ping from the browser using AJAX. 使用AWS API Gateway创建具有适当CORS配置的RESTful端点,您可以使用AJAX从浏览器ping。

Both options have their pros and cons. 两种选择都有其优点和缺点。 More information about your use-case would be necessary to properly evaluate which one suits you best. 有关您的用例的更多信息对于正确评估哪一个最适合您是必要的。

I see people have used AWS SDK for Javascript but it is not required specially since you need to create Amazon Cognito identity pool with access enabled for unauthenticated identities (Atleast for beginners like me). 我看到人们已经使用AWS SDK for Javascript但是并不需要特殊,因为您需要创建具有未经身份验证的身份访问权限的Amazon Cognito身份池(对于像我这样的初学者来说是Atleast)。 Below code works fine for me - 下面的代码对我来说很好 -

<html>
    <head>
<script>
    function callAwsLambdaFunction() {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("myDiv").innerHTML = this.responseText;
            }
        };
        xhttp.open("GET", "https://test123.ap-south-1.amazonaws.com/dev", true);
        xhttp.send();

    }
    </script>   
        <title>Hello World!</title>
    </head>
    <body>
        <h1>Hello world!</h1>
        <h1>Click below button to call API gatway and display result below!</h1>
        <h1><div id="myDiv"></div></h1>
        <button onclick="callAwsLambdaFunction()">Click me!</button><br>
        Regards,<br/>
        Aniket
    </body>
</html>

Above is sample index.html that I have added to my S3 bucket and made a static site. 上面是我添加到S3存储桶并创建静态站点的示例index.html。 Couple of points to note - 几点要注意 -

  1. Make your index.html open from outside if you are using S3 for static site hosting. 如果您使用S3进行静态站点托管,请从外部打开index.html。
  2. Make sure you turn on CORS for your API gateway if your website domain is not same as API gateway domain. 如果您的网站域与API网关域不同,请确保为API网关启用CORS。 Else you might get - 否则你可能得到 -

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://test123.ap-south-1.amazonaws.com/dev. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

For people who see this after 2017, you can check out AWS Amplify API class . 对于2017年之后看到此内容的人,您可以查看AWS Amplify API类 The sample code is taken from Amplify API document. 示例代码取自Amplify API文档。

Note that 注意
1) You have to use POST method to invoke lambda functions. 1)您必须使用POST方法来调用lambda函数。
2) Make sure to add policy to invoke lambda permission for your unauthenticated(if needed) and authenticated roles. 2)确保添加策略以调用未经身份验证(如果需要)和经过身份验证的角色的lambda权限。
3) User doesn't need to sign in to invoke the lambda if a permission policy is granted. 3)如果授予了权限策略,则用户无需登录即可调用lambda。

import Amplify, { API } from 'aws-amplify';

Amplify.configure({
    Auth: {
    // REQUIRED - Amazon Cognito Identity Pool ID
        identityPoolId: 'XX-XXXX-X:XXXXXXXX-XXXX-1234-abcd-1234567890ab',
    // REQUIRED - Amazon Cognito Region
        region: 'XX-XXXX-X', 
    // OPTIONAL - Amazon Cognito User Pool ID
        userPoolId: 'XX-XXXX-X_abcd1234', 
    // OPTIONAL - Amazon Cognito Web Client ID
        userPoolWebClientId: 'XX-XXXX-X_abcd1234',
    },
    API: {
        endpoints: [ 
            {
                name: "MyCustomLambdaApi",
                endpoint: "https://lambda.us-east-1.amazonaws.com/2015-03-31/functions/yourFuncName/invocations",
                service: "lambda",
                region: "us-east-1"
            }
        ]
    }
});

This is how you call your lambda function 这就是你如何调用lambda函数

let apiName = 'MyApiName'; // replace this with your api name.
let path = '/path'; //replace this with the path you have configured on your API
let myInit = {
    body: {}, // replace this with attributes you need
    headers: {} // OPTIONAL
}

API.post(apiName, path, myInit).then(response => {
    // Add your code here
});

I would use AWS SDK for Javascript, below the steps 我会在步骤下面使用AWS SDK for Javascript

  1. Reference the js file 引用js文件

    <script src="https://sdk.amazonaws.com/js/aws-sdk-2.100.0.min.js"></script>

  2. Initialize/Configure the SDK 初始化/配置SDK

    AWS.config.update({region: 'REGION'}); AWS.config.credentials = new AWS.CognitoIdentityCredentials({IdentityPoolId: 'IdentityPool'});

  3. Create the service lambda Object and so on... 创建服务lambda对象等等......

you can see the next steps in this link 您可以在此链接中看到后续步骤

http://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/browser-invoke-lambda-function-example.html http://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/browser-invoke-lambda-function-example.html

Invoke AWS Lambda Using No API Gateway ||使用 API 网关调用 AWS Lambda || Using no AWS SDK不使用 AWS SDK

Assumption is that you've made your function url and made the necessary cross-origin settings.假设您已经设置了 function url 并进行了必要的跨域设置。 Both can be done on the configuration tab of the lambda function Assumption is that the lambda is written in python, but called from javascript两者都可以在 lambda 的配置选项卡上完成 function 假设 lambda 写入 python,但从 javascript 调用

1. Write the function 1.写function

The payload is retrieved from the event variable The format for the event variable is given by aws从事件变量中检索有效负载事件变量的格式由aws给出

def lambda_handler(event, context): payload = event["rawQueryString"] return { "payload": payload }

2. Use a simple fetch to your function URL 2. 使用简单的获取到您的 function URL

In the example, you want to send a name and password to the function在示例中,您想将namepassword发送到 function

 fetch('https://aws-lambda-function-url?name=jason&password=1234').then((response) => response.json()).then((data) => console.log(data));

3. Result 3.结果

{payload: 'name=jason&password=1234'} {payload: 'name=jason&password=1234'}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从 AWS CodePipeline 调用 AWS Lambda function 时权限被拒绝 - Permission denied when calling AWS Lambda function from AWS CodePipeline aws cdk lambda,appconfig typescript 示例好吗? - aws cdk lambda, appconfig typescript example please? 尝试运行示例“R on AWS Lambda with Containers” - Trying to run example "R on AWS Lambda with Containers" 调用 AWS SSO 权限集时从 Lambda function 获取 AccessDeniedException - Getting AccessDeniedException from Lambda function when calling AWS SSO Permission set AWS SAM - HttpApi 与 Lambda Function 集成的简单示例 - AWS SAM - Simple example of HttpApi with Lambda Function Integration AWS Lambda function 调用 aws 服务超时 - AWS Lambda function timing out on calling aws service 从 AWS Lambda 调用 invoke_endpoint 进行语义分割 model 返回 application/x-recordio-protobuf 而不是图像 (Python) - Calling invoke_endpoint from AWS Lambda for a semantic segmentation model returning application/x-recordio-protobuf instead of image (Python) 如何从 s3 存储桶解析 CSV 以在 javascript AWS Lambda function 中使用 - How to parse CSVs from s3 bucket to use in a javascript AWS Lambda function AWS Lambda:调用调用 API 操作失败并显示此消息:网络错误 - AWS Lambda : Calling the invoke API action failed with this message: Network Error 在 AWS 的 Lambda Function 中调用时无法访问“事件”属性 - Can't access 'event' properties when calling it in Lambda Function in AWS
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM