I have the node.js code below (following Getting Started with REST APIs in Amazon API Gateway):
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 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 jQuery ajax method to pass the "name" variable?
The ajax code that 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 alerts an error when I run it.
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):
$.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'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}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With