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.
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.
Please include a complete HTML example, not just a code snippet.
js server you can just invoke your lambda directly with the AWS JavaScript SDK(https://www.npmjs.com/package/aws-sdk). This way you don't have to worry about using API Gateway. Which trigger configuration to choose for invoking it from server?
AWS Lambda is a serverless compute service that lets you run code without provisioning or managing servers, creating workload-aware cluster scaling logic, maintaining event integrations, or managing runtimes. AWS SDK for JavaScript v2, and not v3, is installed in the default Lambda Node. js environment.
Looks like an ability to directly call Lambdas over the Internet without an API Gateway was just added to the SDK. Function URLs are available using the Lambda API and are supported in CloudFormation, AWS SAM and AWS CDK.
You can invoke Lambda functions directly using the Lambda console, a function URL HTTP(S) endpoint, the Lambda API, an AWS SDK, the AWS Command Line Interface (AWS CLI), and AWS toolkits.
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 -
<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 -
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With