首页 > 解决方案 > 如何使用 api url 从 lambda 函数获取响应到 ajax 调用

问题描述

我创建了 lambda 函数和 api(get 方法),然后映射它们并部署。

api-url:https://**********.execute-api.*********.amazonaws.com/test 当我打开这个网址时,我得到了以下输出。

{"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)
    }

阿贾克斯调用:

<!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调用它将进入错误部分

案例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 时。

很少有事情会失败,为什么?

在此处输入图像描述

有什么建议么?

谢谢。

标签: ajaxamazon-web-servicesaws-lambdaamazon-api-gateway

解决方案


推荐阅读