[英]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
,因此您可以使用两个选项来实现它。
Use AWS Javascript SDK
, set it up with user via static configuration or Cognito
with IAM Permissions
to your Lambda
. 使用
AWS Javascript SDK
,通过静态配置向用户设置,或者通过IAM Permissions
将Cognito
设置为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方法还需要您通过单独调用来存储和检索提交状态。
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 -
几点要注意 -
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
Reference the js file 引用js文件
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.100.0.min.js"></script>
Initialize/Configure the SDK 初始化/配置SDK
AWS.config.update({region: 'REGION'}); AWS.config.credentials = new AWS.CognitoIdentityCredentials({IdentityPoolId: 'IdentityPool'});
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
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 调用
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 }
In the example, you want to send a name
and password
to the function在示例中,您想将
name
和password
发送到 function
fetch('https://aws-lambda-function-url?name=jason&password=1234').then((response) => response.json()).then((data) => console.log(data));
{payload: 'name=jason&password=1234'}
{payload: 'name=jason&password=1234'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.