AWS Lambda - 网关因 CORS 策略问题而被阻止

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

我正在尝试设置登录并注册 lambda 函数。它们都通过 OPTION CORS 方法设置为 POST。两者具有相同的配置。登录工作没有问题,但注册给我这个错误。 CRUD 操作也给了我同样的错误。只需登录即可工作。我希望有人能帮忙

API网关结构

enter image description here

方法响应 enter image description here

集成响应 enter image description here

Access to XMLHttpRequest at 'https://88106yumrk.execute-api.eu-north-1.amazonaws.com/prod/auth/register' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Register.js:31 Registration error: AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK', config: {…}, request: XMLHttpRequest, …}
overrideMethod @ console.js:273
handleRegister @ Register.js:31
await in handleRegister (async)
callCallback @ react-dom.development.js:4164
invokeGuardedCallbackDev @ react-dom.development.js:4213
invokeGuardedCallback @ react-dom.development.js:4277
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4291
executeDispatch @ react-dom.development.js:9041
processDispatchQueueItemsInOrder @ react-dom.development.js:9073
processDispatchQueue @ react-dom.development.js:9086
dispatchEventsForPlugins @ react-dom.development.js:9097
(anonymous) @ react-dom.development.js:9288
batchedUpdates$1 @ react-dom.development.js:26179
batchedUpdates @ react-dom.development.js:3991
dispatchEventForPluginEventSystem @ react-dom.development.js:9287
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ react-dom.development.js:6465
dispatchEvent @ react-dom.development.js:6457
dispatchDiscreteEvent @ react-dom.development.js:6430
Show 16 more frames
Show less
Register.js:17 
        
        
       POST https://88106yumrk.execute-api.eu-north-1.amazonaws.com/prod/auth/register net::ERR_FAILED 400 (Bad Request)

我不小心将我的注册覆盖到了我的loginLambda 函数中。并且注册没有问题。我试图检查出了什么问题,但我无法理解问题所在。

这是我的 lambda 函数

登录用户

const { DynamoDBClient, QueryCommand } = require("@aws-sdk/client-dynamodb");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");

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

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

  let body;
  try {
    body = JSON.parse(event.body);
  } catch (error) {
    return {
      statusCode: 400,
      headers: {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "OPTIONS,POST,GET,PUT,DELETE",
        "Access-Control-Allow-Headers":
          "Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token",
      },
      body: JSON.stringify({ error: "Invalid JSON format in request body" }),
    };
  }

  const { username, password } = body;

  const params = {
    TableName: "users",
    IndexName: "username-index",
    KeyConditionExpression: "username = :username",
    ExpressionAttributeValues: {
      ":username": { S: username },
    },
  };

  try {
    const command = new QueryCommand(params);
    const result = await client.send(command);
    if (result.Items.length === 0) {
      console.log("No user found with username:", username);
      return {
        statusCode: 400,
        headers: {
          "Access-Control-Allow-Origin": "*",
          "Access-Control-Allow-Methods": "OPTIONS,POST,GET,PUT,DELETE",
          "Access-Control-Allow-Headers":
            "Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token",
        },
        body: JSON.stringify({ message: "Invalid credentials" }),
      };
    }

    const user = result.Items[0];
    console.log("User found:", user);

    const isPasswordValid = await bcrypt.compare(password, user.password.S);
    console.log("Password is valid:", isPasswordValid);

    if (!isPasswordValid) {
      console.log("Invalid password for username:", username);
      return {
        statusCode: 400,
        headers: {
          "Access-Control-Allow-Origin": "*",
          "Access-Control-Allow-Methods": "OPTIONS,POST,GET,PUT,DELETE",
          "Access-Control-Allow-Headers":
            "Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token",
        },
        body: JSON.stringify({ message: "Invalid credentials" }),
      };
    }

    const token = jwt.sign({ userId: user.userId.S }, process.env.JWT_SECRET, {
      expiresIn: "1h",
    });
    console.log("Generated token:", token);

    return {
      statusCode: 200,
      headers: {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "OPTIONS,POST,GET,PUT,DELETE",
        "Access-Control-Allow-Headers":
          "Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token",
      },
      body: JSON.stringify({ token }),
    };
  } catch (error) {
    console.error("Login error:", error);
    return {
      statusCode: 500,
      headers: {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "OPTIONS,POST,GET,PUT,DELETE",
        "Access-Control-Allow-Headers":
          "Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token",
      },
      body: JSON.stringify({ error: "Could not log in user" }),
    };
  }
};

注册用户

const { DynamoDBClient, PutItemCommand } = require("@aws-sdk/client-dynamodb");
const bcrypt = require("bcryptjs");
const { v4: uuidv4 } = require("uuid");

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

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

  let body;
  try {
    body = JSON.parse(event.body);
  } catch (error) {
    return {
      statusCode: 400,
      headers: {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "OPTIONS,POST,GET,PUT,DELETE",
        "Access-Control-Allow-Headers":
          "Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token",
      },
      body: JSON.stringify({ error: "Invalid JSON format in request body" }),
    };
  }

  const { username, password } = body;

  const hashedPassword = await bcrypt.hash(password, 10);
  const userId = uuidv4();

  const params = {
    TableName: "users",
    Item: {
      userId: { S: userId },
      username: { S: username },
      password: { S: hashedPassword },
    },
  };

  try {
    const command = new PutItemCommand(params);
    await client.send(command);
    console.log("User successfully created:", { userId, username });

    return {
      statusCode: 201,
      headers: {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "OPTIONS,POST,GET,PUT,DELETE",
        "Access-Control-Allow-Headers":
          "Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token",
      },
      body: JSON.stringify({ message: "User registered successfully" }),
    };
  } catch (error) {
    console.error("Registration error:", error);
    return {
      statusCode: 500,
      headers: {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Methods": "OPTIONS,POST,GET,PUT,DELETE",
        "Access-Control-Allow-Headers":
          "Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token",
      },
      body: JSON.stringify({ error: "Could not register user" }),
    };
  }
};
amazon-web-services aws-lambda aws-api-gateway cicd
1个回答
0
投票

我们之前也经历过同样的情况,我们所做的是在函数顶部安装一个条件,以处理返回立即

200
(如果调用该函数的 http 方法是
OPTIONS
)。


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",
    },
  };
}

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

exports.handler = async (event) => {
   try {
     if (isCors(event)) {
       return respond(200, {});
     }

     return respond(200, { message: "User registered successfully" });
   } catch (err) {
     return respond(500, {});
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.