AWS Lambda / CRUD operations gateway blocked by CORS policy problem

I am trying to implement CRUD opretaions to my Lambda with API Gateway, you can see the implementations of my tools and the error. Even the headers are matched correct I still get the access errors

Structure of API Gateway

Here are my lambda functions

todosHandler

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> 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" });
};
</code>
<code> 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" }); }; </code>
    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" });
};

the error of todos

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> {
"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"
}
}
}
</code>
<code> { "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" } } } </code>
 {
    "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"
        }
    }
}

Mapping Teamplate for Integration Response for GET

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>#set($inputRoot = $input.path('$'))
{
"statusCode": 200,
"body": $input.json('$')
}
</code>
<code>#set($inputRoot = $input.path('$')) { "statusCode": 200, "body": $input.json('$') } </code>
#set($inputRoot = $input.path('$'))
{
  "statusCode": 200,
  "body": $input.json('$')
}

Mapping Teamplate for Integration Request for GET

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>{
"queryStringParameters": {
"userId": "$input.params('userId')"
}
}
</code>
<code>{ "queryStringParameters": { "userId": "$input.params('userId')" } } </code>
{
  "queryStringParameters": {
    "userId": "$input.params('userId')"
  }
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật