简体   繁体   English

无法使用无服务器通过 AWS Lambda 和 DynamoDB Rest API 发送 GET 请求

[英]Unable to send GET request with AWS Lambda & DynamoDB Rest API using serverless

I am creating an API to make GET and POST request to a table in DynamoDB.我正在创建一个 API 来向 DynamoDB 中的表发出 GET 和 POST 请求。

I deployed it using serverless and received the endpoints for each API type.我使用无服务器部署它并接收每个 API 类型的端点。

But when testing it out with Postman I get the following error:但是在使用 Postman 进行测试时,出现以下错误:

Bad request. We can't connect to the server for this app or website at this time. There might be too much traffic or a configuration error. Try again later, or contact the app or website owner. 
If you provide content to customers through CloudFront, you can find steps to troubleshoot and help prevent this error by reviewing the CloudFront documentation. 

Code for creating the data in the table:在表中创建数据的代码:


const postsTable = process.env.POSTS_TABLE;
// Create a response
function response(statusCode, message) {
    return {
        statusCode: statusCode,
        body: JSON.stringify(message)
    };
}

// Create a post
module.exports.createPost = (event, context, callback) => {
    const reqBody = JSON.parse(event.body);

    if (
        !reqBody.title ||
        reqBody.title.trim() === "" ||
        !reqBody.body ||
        reqBody.body.trim() === ""
    ) {
        return callback(
            null,
            response(400, {
                error:
                    "Post must have a title and body and they must not be empty"
            })
        );
    }

    const post = {
        id: uuidv4(),
        createdAt: new Date().toISOString(),
        userId: 1,
        title: reqBody.title,
        body: reqBody.body
    };

    return db
        .put({
            TableName: postsTable,
            Item: post
        })
        .promise()
        .then(() => {
            callback(null, response(201, post));
        })
        .catch(err => response(null, response(err.statusCode, err)));
};

I managed to do it but did not use Serverless.我设法做到了,但没有使用无服务器。

I set up Lambda functions to POST and GET the data from a url.我设置了 Lambda 函数以从 url POST 和 GET 数据。

I think the issue previously was to do with the policies.我认为以前的问题与政策有关。 This time when making the Lambda functions I set it as the following:这次在制作 Lambda 函数时,我将其设置如下:

I clicked on "Create a new role from AWS policy templates" while creating an execution role for a new function, then selected "Simple microservice permissions" for Policy templates.我在为新功能创建执行角色时单击了“从 AWS 策略模板创建新角色”,然后为策略模板选择了“简单微服务权限”。 This added Basic execution role policy and below DynamoDB permissions to the role for all the tables in the same region as the function :这为与函数位于同一区域的所有表的角色添加了基本执行角色策略和以下 DynamoDB 权限:

"Action": [
               "dynamodb:DeleteItem",
               "dynamodb:GetItem",
               "dynamodb:PutItem",
               "dynamodb:Scan",
               "dynamodb:UpdateItem"
           ]

Lambda function for POST request POST 请求的 Lambda 函数

exports.handler = async (event, context) => {
    const ddb = new AWS.DynamoDB({ apiVersion: "2012-10-08" });
    const documentClient = new AWS.DynamoDB.DocumentClient({
        region: "ap-southeast-1"
    });

    let responseBody = "";
    let statusCode = 0;

    const {
        deviceId,
        batteryLevel,
        eventId,
        id,
        location,
        tags,
        time
    } = JSON.parse(event.body);

    const params = {
        TableName: "dashboard",
        Item: {
            batteryLevel: batteryLevel,
            deviceId: deviceId,
            eventId: eventId,
            location: location,
            tags: tags,
            time: time
        }
    };

    try {
        const data = await documentClient.put(params).promise();
        responseBody = JSON.stringify(data);
        statusCode = 201;
    } catch (err) {
        responseBody = "Unable to POST data";
        statusCode = 403;
    }
    const response = {
        statusCode: statusCode,
        headers: {
            myHeader: "test"
        },
        body: responseBody
    };
    return response;
};

Other issues as well were with the method execution of the API I needed to set a custom model for the Request Body to match my data:其他问题也与 API 的方法执行有关,我需要为请求正文设置自定义模型以匹配我的数据:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "DashboardInputModel",
  "type": "object",
  "properties": 
  {
  "batteryLevel": {"type": "string"},
  "deviceId": {"type": "string"},
  "eventId": {"type": "string"},
  "id": {"type": "number"},
  "location": {
      "type": "object",
      "properties":{
            "accuracy": {"type": "number"},
            "latitude": {"type": "number"},
            "longitude": {"type": "number"}
      }
  },
  "tags": {
   "type": "array",
      "items": {
        "type": "object",
        "properties": {
      "accelX":{"type": "number"},
      "accelY": {"type": "number"},
      "accelZ": {"type": "number"},
      "createDate": {"type": "string"},
      "dataFormat":{"type": "number"},
      "defaultBackground": {"type": "number"},
      "favorite": {"type": "boolean"},
      "humidity": {"type": "number"},
      "id": {"type": "string"},
      "measurementSequenceNumber": {"type": "number"},
      "movementCounter": {"type": "number"},
      "name": {"type": "string"},
      "pressure": {"type": "number"},
      "rssi": {"type": "number"},
      "temperature": {"type": "number"},
      "txPower":{"type": "number"},
      "updateAt": {"type": "string"},
      "voltage": {"type": "number"}
        }
    }   
  },
  "time": {"type": "string"}
}
}

For each action I also enabled CORS and replaced the existing CORS headers.对于每个操作,我还启用了 CORS 并替换了现有的 CORS 标头。

These two videos explains the entire process much better than the documentation and I hope it helps.这两个视频比文档更好地解释了整个过程,我希望它有所帮助。

Part 1第1部分

Part 2第2部分

By bad request do you mean Status Code 400? 错误的请求是指状态代码 400 吗? It could simply be that you are not correctly calling your API. 可能只是您没有正确调用 API。

If you are getting a 403 then you need to pass through that you are authorised to access the resource you are trying to get.如果您收到 403,那么您需要通过您有权访问您尝试获取的资源的信息。 You can see how to do this through the AWS docs .您可以通过 AWS 文档了解如何执行此操作。

This page includes a link to an example.此页面包含指向示例的链接。

List of error codes .错误代码列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在使用无服务器框架时从AWS Lambda访问DynamoDB? - How to access DynamoDB from AWS Lambda when using the Serverless Framework? 无法使用 aws serverless 离线从另一个 lambda 调用 lambda - Unable to invoke a lambda from another lambda using aws serverless offline 无服务器框架、yaml 和 AWS lambda/DynamoDB 概念 - Serverless framework, yaml and AWS lambda/DynamoDB concepts 适用于 Lambda 无服务器架构的 AWS DynamoDB 与 RDS - AWS DynamoDB vs RDS for Lambda serverless architecture AWS无服务器API请求 - AWS Serverless API Request 无服务器框架+ AWS + Lambda + DynamoDB + GraphQL + Apollo服务器=无法使POST请求生效 - Serverless framework + AWS + Lambda + DynamoDB + GraphQL + Apollo Server = Can't make POST Request Work 无法将 ${cognito-identity.amazonaws.com:sub} 中的 lambda 策略与无服务器和 DynamoDB/Cognito/API 网关一起使用 - Unable to use ${cognito-identity.amazonaws.com:sub} in lambda policy with serverless and DynamoDB/Cognito/API Gateway 使用 API 网关和无服务器框架在 AWS Lambda 上超过了速率 - Rate Exceeded on AWS Lambda Using API Gateway and serverless framework AWS Lambda-使用.NET Core构建无服务器API - AWS Lambda - Building serverless API using .NET Core AWS lambda 无法读取 dynamodb 表并使用 sendgrid 发送邮件 - AWS lambda cannot read dynamodb table and send mail using sendgrid
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM