Sending a HTTP Post Request correctly

2019-09-11 04:13发布

问题:

I have a simple AWS Lambda function that must receive HTTP Post data and print it:

AWS Lambda function

var aws = require('aws-sdk');
var querystring = require('querystring');
var ses = new aws.SES();

exports.handler = function(event, context) {
    console.log("Incoming: ", event);             
};

My HTML form:

<form action="http://myawsfuncurl" method="POST">
   <input type="textarea" width="200" height="100" value="Hello"><br>
   <input type="submit" value="Send">
</form>

The console simply prints: Incoming: {}
No data is received.

However, this works fine when i send HTTP Post via a java code:

Java Code

URL obj = new URL("http://myawsfuncurl");
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

String payload = "hello";

// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(payload);
wr.flush();
wr.close();

How can i make it work via HTML form too?

回答1:

I had the same issue trying to send it via http POST form.

I got around this by sending it via an Ajax request which sends JSON data to the function.

Something like this should hopefully help. If you put it in a script tag on your html page.

<script>
    $.support.cors = true;
    $('#id_of_form').submit(function(event){
        event.preventDefault();         
        $.ajax(
            {
                type: 'POST',
                url: 'http://myawsfuncurl',                 
                dataType: 'json',
                data: {
                    ParamA: $('#id_of_textarea").text()                 
                },
                error: function(obj, msg, exc){},
                success: function(data){
                   alert('complete');                       
                }
            }
        )

        return false;
    });
</script>