AWS Lambda / CRUD 操作网关因 CORS 策略问题而被阻止

问题描述 投票:0回答:1

我正在尝试使用 API Gateway 对我的 Lambda 实现 CRUD 操作,您可以看到我的工具的实现和错误。即使标头匹配正确,我仍然遇到访问错误

API网关结构

enter image description here

enter image description here

enter image description here

这是我的 lambda 函数

todosHandler

    const {
  DynamoDBClient,
  QueryCommand,
  PutItemCommand,
  UpdateItemCommand,
  DeleteItemCommand,
} = require("@aws-sdk/client-dynamodb");
const { marshall, unmarshall } = require("@aws-sdk/util-dynamodb");

const client = new DynamoDBClient({ region: process.env.AWS_REGION });

function respond(statusCode, body) {
  return {
    statusCode,
    body: JSON.stringify(body),
    headers: {
      "Content-Type": "application/json",
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Headers":
        "Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token",
      "Access-Control-Allow-Methods": "OPTIONS,POST,GET,PUT,DELETE",
    },
  };
}

function isCors(event) {
  return (event?.httpMethod || "").toLowerCase() === "options";
}

exports.handler = async (event) => {
  console.log("Received event:", JSON.stringify(event, null, 2));

  if (isCors(event)) {
    return respond(200, {});
  }

  try {
    switch (event.httpMethod) {
      case "GET":
        return await handleRequest(getTodos, event);
      case "POST":
        return await handleRequest(createTodo, event);
      case "PUT":
        return await handleRequest(updateTodo, event);
      case "DELETE":
        return await handleRequest(deleteTodo, event);
      default:
        return respond(400, { message: "Unsupported method" });
    }
  } catch (err) {
    console.error("Error processing request:", err);
    return respond(500, { error: "Could not process request" });
  }
};

const handleRequest = async (handler, event) => {
  try {
    return await handler(event);
  } catch (err) {
    console.error("Error in handler:", err);
    throw err;
  }
};

const getTodos = async (event) => {
  console.log("Handling GET request:", JSON.stringify(event, null, 2));

  const userId = event.queryStringParameters.userId;
  const params = {
    TableName: "todos",
    KeyConditionExpression: "userId = :userId",
    ExpressionAttributeValues: marshall({ ":userId": userId }),
  };

  const data = await client.send(new QueryCommand(params));
  console.log("Query successful:", JSON.stringify(data, null, 2));
  return respond(
    200,
    data.Items.map((item) => unmarshall(item))
  );
};

const createTodo = async (event) => {
  console.log("Handling POST request:", JSON.stringify(event, null, 2));

  const todo = JSON.parse(event.body);
  const params = {
    TableName: "todos",
    Item: marshall(todo),
  };

  await client.send(new PutItemCommand(params));
  console.log("Todo created successfully");
  return respond(201, { message: "Todo created successfully" });
};

const updateTodo = async (event) => {
  console.log("Handling PUT request:", JSON.stringify(event, null, 2));

  const { todoId, userId, ...updates } = JSON.parse(event.body);
  const updateExpression = [];
  const expressionAttributeValues = {};

  for (const key in updates) {
    if (updates[key] !== undefined) {
      updateExpression.push(`${key} = :${key}`);
      expressionAttributeValues[`:${key}`] = updates[key];
    }
  }

  const params = {
    TableName: "todos",
    Key: marshall({ todoId, userId }),
    UpdateExpression: `set ${updateExpression.join(", ")}`,
    ExpressionAttributeValues: marshall(expressionAttributeValues),
    ReturnValues: "ALL_NEW",
  };

  const data = await client.send(new UpdateItemCommand(params));
  console.log("Todo updated successfully:", JSON.stringify(data, null, 2));
  return respond(200, unmarshall(data.Attributes));
};

const deleteTodo = async (event) => {
  console.log("Handling DELETE request:", JSON.stringify(event, null, 2));

  const { todoId, userId } = JSON.parse(event.body);
  const params = {
    TableName: "todos",
    Key: marshall({ todoId, userId }),
  };

  await client.send(new DeleteItemCommand(params));
  console.log("Todo deleted successfully");
  return respond(200, { message: "Todo deleted successfully" });
};

待办事项的错误

 {
    "statusCode": 200,
    "body": {
        "statusCode": 400,
        "body": "{\"message\":\"Unsupported method\"}",
        "headers": {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Headers": "Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token",
            "Access-Control-Allow-Methods": "OPTIONS,POST,GET,PUT,DELETE"
        }
    }
}

映射 GET 集成响应的团队板

#set($inputRoot = $input.path('$'))
{
  "statusCode": 200,
  "body": $input.json('$')
}

映射 GET 集成请求的团队板

{
  "queryStringParameters": {
    "userId": "$input.params('userId')"
  }
}
amazon-web-services aws-lambda cors aws-api-gateway cicd
1个回答
0
投票

以下是解决该问题的一些步骤

  • 确保 API Gateway 中的每个方法都启用 CORS。
  • 验证 API Gateway 中的方法是否链接到正确的 lambda 函数。
  • 尝试在 lambda 的开头和结尾添加更多日志记录,例如接收到的事件数据、创建的响应等。
  • 使用浏览器开发人员工具中的 Postman 和网络/控制台选项卡来检查完整的请求/响应详细信息和错误。
  • 确保在正确的阶段对 API 进行任何修改后部署更改。
© www.soinside.com 2019 - 2024. All rights reserved.