我下面有node.js代码(遵循Amazon API Gateway中的REST API入门):
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
};
但是我不知道如何使用jQuery ajax方法将“名称”参数传递给该代码。它在我使用时有效:
curl -H "Content-Type: application/json" -X POST -d "{\"name\": \"PeterChan\"}" https://my-api-id.execute-api.region-id.amazonaws.com/test/mydemoresource
我可以得到结果:
{"Hello":"User"}
但是如何使用jQuery ajax方法传递“名称”变量?
我写的ajax代码:
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");
}
});
当我运行它时,它会警告错误。
因此,看来您可能有几个问题。一,避免使用“名称”作为变量名称。第二,数据可能未正确解析。发送时需要JSON.Stringify(是的,您已经有JSON,但这很挑剔):
$.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
}
});
我还添加了crossDomain:true和contentType:'application / json'。
在lambda函数中获取传入的JSON中的键/值时,您只需使用event.whateverkey(在Lambda控制台中使用test事件时,使键与您要发送的键匹配,以避免出现任何问题)。
ambx函数返回的成功回调中的数据是从lambda函数返回的数据,因此,我建议在lambda函数中使用JSON.stringifying该数据,而不是确保其正确发送的成功消息:
context.done(null, JSON.stringify({"Hello":name}));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句