как получить ответ от лямбда-функции на вызов ajax с использованием URL-адреса API
Я создал лямбда-функцию и api (метод получения), затем сопоставил их и развернул.
api-url: https: //**********.execute-api.*********.amazonaws.com/test, когда я открываю этот URL, я получаю результат ниже.
{"statusCode": 200, "headers": {"Content-Type": "application/json"}, "body": "{\"message\": \"new subject area added successfully\"}"}
лямбда-функция:
import json
def lambda_handler(event, context):
message={
'message':'new subject area added successfully'
}
return {
'statusCode': 200,
'headers': {'Content-Type': 'application/json'},
'body': json.dumps(message)
}
Вызов Ajax:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function addSubjectArea() {
alert("going to call ajax");
$.ajax({
url: 'https://37l42zsugg.execute-api.us-east-1.amazonaws.com/test',
type: 'GET',
crossDomain: true,
contentType: 'application/json',
success:function(response){
alert(response)
},
error: function (jqXHR, textStatus, errorThrown) {
alert("error occurred while get data");
}
});
}
$(document).ready(function(){
addSubjectArea();
});
</script>
</head>
<body>
<div id="div1"><h2>api call from ajax methoid</h2></div>
</body>
</html>
но из вызова ajax он войдет в раздел ошибок
case-2:
мой шаблон cloudFormation:
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
hello
Sample SAM Template for hello
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
Function:
Timeout: 3
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: hello_world/
Handler: app.lambda_handler
Runtime: python3.6
Events:
HelloWorld:
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
Properties:
Path: /hello2
Method: get
Outputs:
# ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
# Find out more about other implicit resources you can reference within SAM
# https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
HelloWorldApi:
Description: "API Gateway endpoint URL for Prod stage for Hello World function"
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
HelloWorldFunction:
Description: "Hello World Lambda Function ARN"
Value: !GetAtt HelloWorldFunction.Arn
HelloWorldFunctionIamRole:
Description: "Implicit IAM Role created for Hello World function"
Value: !GetAtt HelloWorldFunctionRole.Arn
@@@@ api Ресурс создан успешно, и при попытке включить cors.
несколько вещей могут потерпеть неудачу, почему?
какие-либо предложения?
Спасибо.