TimLee TimLee - 2 years ago 78
Javascript Question

how to use ajax GET or POST method to past data to amazon lambda node.js function

I am a new user for amazon web service. Recently I am studying amazon lambda server and I have a small node.js code as below(following this example:http://docs.aws.amazon.com/apigateway/latest/developerguide/getting-started.html):

console.log('Loading event');

exports.handler = function(event, context) {
var name = (event.name === undefined ? 'No-Name' : event.name);
context.done(null, {"Hello":name}); // SUCCESS with message

But I don't know how to use jquery ajax method to pass "name" parameter to that code. It work when I use:

curl -H "Content-Type: application/json" -X POST -d "{\"name\": \"PeterChan\"}" https://my-api-id.execute-api.region-id.amazonaws.com/test/mydemoresource

and I can get the result:{"Hello":"User"}

but how can I use jquery ajax method to past "name" variable?

The ajax code that I wrote:

var data = {"name":"bbbb"};

type: "POST",
dataType: "json",
data: data,
//processData: false,
success: function(data) {
var text=JSON.stringify(data);

},error: function(data) {

It alert err when I run it. Pleas help.

Thank you~

Answer Source

So it looks like you might have a couple of issues. One, avoid using "name" as a variable name. Two, the data probably isn't being parsed correctly. You need JSON.Stringify when you send it (yeah, you've already got JSON, but it's finicky):

    url: 'https://mylambdafunctionurl/',
    type: 'POST',
    crossDomain: true,
    contentType: 'application/json',
    data: JSON.stringify(data),
    dataType: 'json',
    success: function(data) {
        //success stuff. data here is the response, not your original data
    error: function(xhr, ajaxOptions, thrownError) {
        //error handling stuff

I've also added crossDomain:true, and contentType: 'application/json'.

In the lambda function to get the key/value in the passed in JSON you just use event.whateverkey (when using the test event in the Lambda console make the keys match what you're sending in to avoid any problems).

The data in your success callback in your ajax function is what comes back from the lambda function, so I recommend JSON.stringifying that in the lambda function, and not the success to make sure it gets sent correctly:

context.done(null, JSON.stringify({"Hello":name}));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download