0
我創建了Lambda函數並添加了API網關觸發器。添加觸發器將API創建爲「Lambda代理」和「代理資源」。這很好,因爲每個documentation代理資源「將Lambda函數的輸出轉換爲HTTP響應。」但是,它返回200
,但調用了我的ajax請求的錯誤函數。調試錯誤,我看到parsererror
和No conversion from text to application/json
。 API網關中是否存在缺少的內容?我嘗試將「application/json => Empty
」添加到「方法響應」中,但是沒有執行。AWS API網關和Lambda - 無需將文本轉換爲應用程序/ json
這裏就是我的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:「電子郵件添加到系統。」 }'?如果內容類型是「application/json」,發送一個對象而不是字符串會更有意義。 –
是的,'JSON.parse(「電子郵件添加到系統。」)'拋出一個錯誤。您需要實際提供有效的JSON。 – idbehold
嗯,這打破了功能,並給了我一個502。如果你看看[本]的最底部(https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-set-up -simple-proxy.html#api-gateway-simple-proxy-for-lambda-output-format),'body'需要一個字符串。 – sambol