【发布时间】:2017-03-15 16:37:24
【问题描述】:
我创建了一个 Lambda 函数并添加了一个 API Gateway 触发器。添加触发器将 API 创建为“Lambda 代理”和“代理资源”。这很好,因为根据documentation,代理资源“将 Lambda 函数的输出转换为 HTTP 响应”。但是,它返回 200 但调用了我的 ajax 请求的错误函数。调试错误,我看到parsererror 和No conversion from text to application/json。我在 API Gateway 中缺少什么吗?我尝试将application/json => Empty 添加到“方法响应”但不行。
这是我的 Lambda 函数返回的内容:
return {
"statusCode": 200,
"headers": {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json"
},
"body": "Email added to system."
}
这里是 AJAX:
var formData = $("#submitEmail").serializeArray();
console.log(formData);
$.ajax({
url : "https://<REDACTED>.execute-api.us-east-1.amazonaws.com/prod/SubmitEmail",
type: "POST",
data : formData,
dataType: "application/json",
success: function(data, textStatus, xhr)
{
console.log("SUCCESS")
console.log(xhr.status)
},
error: function (xhr, textStatus, errorThrown)
{
console.log("ERROR")
console.log(xhr.status)
console.log(textStatus)
console.log(errorThrown)
}
});
【问题讨论】:
-
不确定是否会解决,但您可以尝试将正文设置为
"body": { msg: "Email added to system." }吗?如果内容类型是application/json,则发送对象而不是字符串会更有意义。 -
是的,
JSON.parse("Email added to system.")抛出错误。您需要实际提供有效的 JSON。 -
嗯,这会破坏函数并给我一个 502。如果您查看this 的最底部,
body需要一个字符串。 -
@sambol 你需要做的
"body": JSON.stringify({ msg: "Email added to system." })
标签: amazon-web-services lambda aws-lambda aws-api-gateway