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

I am a new user for the amazon web service. I am learning amazon lambda server recently and I have a small node.js code as shown 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 do not know how to use the jQuery ajax method to pass the "name" of this code. It works 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 the jquery ajax method for the last variable "name"?

The ajax code I wrote:

 var data = {"name":"bbbb"}; $.ajax({ type: "POST", dataType: "json", url:"https://my-api-id.execute-api.region-id.amazonaws.com/test/mydemoresource", data: data, //processData: false, success: function(data) { var text=JSON.stringify(data); alert(text); //console.log(data); },error: function(data) { alert("err"); } }); 

It warns about an error when I run it. Please help.

Thanks ~

+5
source share
1 answer

So, it looks like you might have several problems. First, avoid using the name "name" as the name of a variable. Secondly, the data is probably not being processed correctly. You need JSON.Stringify when you submit it (yes, you already have JSON, but this is elusive):

 $.ajax({ 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 also added crossDomain: true and contentType: 'application / json'.

In the lambda function, to get the key / value in the passed to JSON, you simply use event.whateverkey (when using a test event in the Lambda console, the keys correspond to what you send in order to avoid any problems).

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

 context.done(null, JSON.stringify({"Hello":name})); 
+4
source

Source: https://habr.com/ru/post/1235528/


All Articles