我正在尝试使用 API Gateway 对我的 Lambda 实现 CRUD 操作,您可以看到我的工具的实现和错误。即使标头匹配正确,我仍然遇到访问错误
API网关结构
这是我的 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')"
}
}
以下是解决该问题的一些步骤