[英]AWS Lambda & API Gateway - 500 from browser but not from curl
我正在努力應對AWS Lambda和API網關。 我可以通過curl
和Postman調用我的API,但是不能從我的瀏覽器中調用。
這有效
curl --header "Content-Type: application/json" \
--request POST \
--data '{ "baseId" : "app0ZJgZxm6LC8rBB", "tableName": "Stories", "action": "select" }' \
'https://gpzy1rrcwg.execute-api.us-east-1.amazonaws.com/Prod/'
這不起作用 ( 在CodePen上運行它的鏈接 )
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'POST',
url: 'https://gpzy1rrcwg.execute-api.us-east-1.amazonaws.com/Prod/',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({
"baseId" : "app0ZJgZxm6LC8rBB",
"tableName": "Stories",
"action": "select"
}),
success: function (response) {
console.log(response)
alert('it worked')
},
error: function (err) {
console.log(err)
alert('it failed')
}
});
});
});
</script>
</head>
<body>
<button>Test</button>
</body>
</html>
正如@Rup在評論中所說,這可能是CORS問題。 在有關.ajax()的contentType
選項的JQuery文檔中 ,您將看到以下內容:
對於跨域請求,將內容類型設置為application / x-www-form-urlencoded,multipart / form-data或text / plain之外的任何類型,都會觸發瀏覽器向服務器發送預檢OPTIONS請求
通過檢查瀏覽器上的“網絡”標簽,您會看到它正在發送OPTION
請求。 實際上,只需刪除contentType
參數,您的代碼即可按預期運行。
API網關和Lambda之間的集成模式是什么-是基於代理的還是早期的。
您是否在API網關方法中啟用了CORS? https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.