Jesse Barnum
Jesse Barnum

Reputation: 6816

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. 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.

Upvotes: 22

Views: 27789

Answers (5)

Hex Heager
Hex Heager

Reputation: 139

Invoke AWS Lambda Using No API Gateway || Using no AWS SDK

Assumption is that you've made your function url and made the necessary cross-origin settings. 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

1. Write the function

The payload is retrieved from the event variable The format for the event variable is given by aws

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

2. Use a simple fetch to your function URL

In the example, you want to send a name and password to the function

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

3. Result

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

Upvotes: 2

Aniket Thakur
Aniket Thakur

Reputation: 68935

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 -

  1. Make your index.html open from outside if you are using S3 for static site hosting.
  2. 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 -

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).

Upvotes: 10

Jun
Jun

Reputation: 3044

For people who see this after 2017, you can check out AWS Amplify API class. The sample code is taken from Amplify API document.

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.

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

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
});

Upvotes: 5

adamkonrad
adamkonrad

Reputation: 7122

Since you need to run Lambda from the browser, you have two options you can achieve it.

  1. Use AWS Javascript SDK, set it up with user via static configuration or Cognito with IAM Permissions to your Lambda. You can also consider subscribing your Lambda functions to SNS Topic and run the Lambda by sending a message to the topic. This SNS approach would also require you to store and retrieve the submission state via separate call.

  2. Use AWS API Gateway to create RESTful endpoint with proper CORS configuration that you can ping from the browser using AJAX.

Both options have their pros and cons. More information about your use-case would be necessary to properly evaluate which one suits you best.

Upvotes: 12

Oswaldo Zapata
Oswaldo Zapata

Reputation: 693

I would use AWS SDK for Javascript, below the steps

  1. Reference the js file

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

  2. Initialize/Configure the SDK

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

  3. Create the service lambda Object and so on...

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

Upvotes: -1

Related Questions