需要从 JavaScript 调用 AWS Lambda 的示例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32038180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Need example of calling AWS Lambda from JavaScript
提问by Jesse Barnum
Just need an example of how to call AWS Lambda from JavaScript running in a browser and display function result in JavaScript console. Incredibly, I cannot find any examples on Google or from AWS documentation.
只需要一个示例,说明如何从运行在浏览器中的 JavaScript 调用 AWS Lambda 并在 JavaScript 控制台中显示函数结果。令人难以置信的是,我在 Google 或 AWS 文档中找不到任何示例。
My use case is that I have an HTML form. When the form is submitted, I want to use Lambda to process the form inputs. Assuming that the Lambda function finishes with no errors, I then want to take the user to a thank you page.
我的用例是我有一个 HTML 表单。提交表单时,我想使用 Lambda 来处理表单输入。假设 Lambda 函数完成没有错误,然后我想将用户带到感谢页面。
Please include a complete HTML example, not just a code snippet.
请包含完整的 HTML 示例,而不仅仅是代码片段。
采纳答案by Aniket Thakur
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). Below code works fine for me -
我看到有人使用 AWS SDK for Javascript 但它不是特别需要,因为您需要创建 Amazon Cognito 身份池,并为未经身份验证的身份启用访问权限(至少对于像我这样的初学者)。下面的代码对我来说很好用 -
<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. Couple of points to note -
以上是我添加到我的 S3 存储桶并创建了一个静态站点的示例 index.html。需要注意的几点——
- Make your index.html open from outside if you are using S3 for static site hosting.
- Make sure you turn on CORS for your API gateway if your website domain is not same as API gateway domain. Else you might get -
- 如果您使用 S3 进行静态站点托管,请从外部打开您的 index.html。
- 如果您的网站域与 API 网关域不同,请确保为您的 API 网关启用 CORS。否则你可能会得到 -
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).
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).
回答by kixorz
Since you need to run Lambda
from the browser, you have two options you can achieve it.
由于您需要Lambda
从浏览器运行,因此您有两个选项可以实现它。
Use
AWS Javascript SDK
, set it up with user via static configuration orCognito
withIAM Permissions
to yourLambda
. You can also considersubscribing yourLambda
functions toSNS Topic
and run theLambda
by sending a message to the topic. This SNS approach would also require you to store and retrieve the submission state via separate call.Use
AWS API Gateway
to create RESTful endpoint with proper CORS configuration that you can ping from the browser using AJAX.
使用
AWS Javascript SDK
,通过静态配置与用户一起设置或Cognito
使用IAM Permissions
您的Lambda
. 您还可以考虑通过向主题发送消息来订阅您的Lambda
函数SNS Topic
并运行Lambda
。这种 SNS 方法还需要您通过单独的调用来存储和检索提交状态。使用
AWS API Gateway
创建具有适当的CORS配置REST风格的端点,你可以使用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.
这两种选择都有其优点和缺点。需要更多有关您的用例的信息才能正确评估哪一个最适合您。
回答by Jun711
For people who see this after 2017, you can check out AWS Amplify API class. The sample code is taken from Amplify API document.
对于 2017 年后看到此内容的人,您可以查看AWS Amplify API 类。示例代码取自 Amplify API 文档。
Note that
1) You have to use POST method to invoke lambda functions.
2) Make sure to add policy to invoke lambda permission for your unauthenticated(if needed) and authenticated roles.
3) User doesn't need to sign in to invoke the lambda if a permission policy is granted.
请注意
1) 您必须使用 POST 方法来调用 lambda 函数。
2) 确保添加策略以调用未经身份验证(如果需要)和经过身份验证的角色的 lambda 权限。
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
});
回答by Oswaldo
I would use AWS SDK for Javascript, below the steps
我将使用 AWS SDK for Javascript,在步骤下方
Reference the js file
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.100.0.min.js"></script>
Initialize/Configure the SDK
AWS.config.update({region: 'REGION'}); AWS.config.credentials = new AWS.CognitoIdentityCredentials({IdentityPoolId: 'IdentityPool'});
Create the service lambda Object and so on...
引用js文件
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.100.0.min.js"></script>
初始化/配置 SDK
AWS.config.update({region: 'REGION'}); AWS.config.credentials = new AWS.CognitoIdentityCredentials({IdentityPoolId: 'IdentityPool'});
创建服务 lambda 对象等等...
you can see the next steps in this link
您可以在此链接中看到后续步骤