Ad

Calling AWS Lambda From Browser Using Javascript, How Do I Send Input Value To The Function?

I've been trying to call my AWS Lambda function (through Api Gateway rest) which is written in Java that takes as input an Object parameter which is afterwards treated as a simple String. I've tested it through the AWS Lambda Console and through a rest client like Postman and it works fine. This is my Java handler:

public class LambdaInsertMessage implements RequestHandler<Object, String>{

    @Override
    public String handleRequest(Object obj, Context context) {
        String input = obj.toString();
        //insert input in my database
        return "ok";
    }
}

Now I'm trying to integrate it in my html web page (which is in my S3 bucket configured for public static website hosting). This is my Javascript piece of code:

    /*
    * Takes the message inserted in the textarea and send it to my Lambda
    */
    function sendMessage() {
        var message = document.getElementById('messageInput').value;
        var xhttp = new XMLHttpRequest();
        xhttp.open("GET", "https://xxx.execute-api.us-east-1.amazonaws.com/insert", true);
        xhttp.send(message);
    }

This is not working, because the Lambda function is invoked correctly but it receives an empty object as input and not the message that I've inserted in the page (var message is correctly valorized when I'm debugging my browser console).

I have another Lambda call in the page which is a simple hello world where I don't add any data in input and the Lambda works correctly, I'm able to log the response sent by my Lambda function:

    function helloWorld() {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                console.log(this.responseText);
            }
        };
        xhttp.open("GET", "https://xxxx.execute-api.us-east-1.amazonaws.com/helloWorld", true);
        xhttp.send();
    }

So my problem is that in my html page I'm able to retrieve data from my Lambda functions but not to send input data to them. What am I doing wrong?

Thank you for your help!

Ad

Answer

You are sending input to the API, shouldn't it be using the "POST" method when calling the xhttp.open?

xhttp.open("POST", "https://xxx.execute-api.us-east-1.amazonaws.com/insert", true);
Ad
source: stackoverflow.com
Ad