Cors issue for only POST request

0

I'm having cors issue ONLY for my post request. When I make the request I get 204 for OPTIONS but 400 for actual request, I'm using cdk and sns topic in my lambda function too, I've already enabled the cors in my API stack: const api = new RestApi(this, "SB-Api");

const optionsWithCors: ResourceOptions = {
  defaultCorsPreflightOptions: {
    allowOrigins: Cors.ALL_ORIGINS,
    allowMethods: Cors.ALL_METHODS,
  },
};

const formResource = api.root.addResource("form", optionsWithCors);

formResource.addMethod("GET", props.SBLambdaFormIntegration);
formResource.addMethod("POST", props.SBLambdaFormIntegration);

Here is my lambda handler: const ddbClient = new DynamoDBClient({});

const snsClient = new SNSClient({ region: process.env.AWS_REGION });

async function handler(event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> { let response: APIGatewayProxyResult;

try { switch (event.httpMethod) { // case 'GET': // message = 'Get'; // break;

  case 'POST':
    const postRespnse = await postInquiry(event, ddbClient, snsClient);
    response = postRespnse;
    break;
  default:
    break;
}

} catch (error: any) { if (error instanceof JSONError) { return { statusCode: 400, body: error.message, }; } return { statusCode: 400, body: JSON.stringify(error.message), }; }

addCorsHeader(response!); return response!; }

export { handler }; And here is my postInquiry function: export async function postInquiry( event: APIGatewayProxyEvent, ddbClient: DynamoDBClient, snsClient: SNSClient ): Promise<APIGatewayProxyResult> { const randomId = v4();

const item: InquiryForm = parseJSON(event.body);

item.id = randomId;

validateAsInquiryEntry(item);

await ddbClient.send( new PutItemCommand({ TableName: process.env.TABLE_NAME, Item: marshall(item), }) );

const snsTopicArn = process.env.SNS_TOPIC_ARN;

const snsPublishParams = { TopicArn: snsTopicArn, Message: `Hello,

You have a new request From: ${item.firstName} ${item.lastName} Email: ${item.email} Phone: ${formatPhoneNumber(item.phone)}`, };

await snsClient.send(new PublishCommand(snsPublishParams));

return { statusCode: 201, body: JSON.stringify("OK"), }; }

I really appreciate your help

  • The code isn't very clear on where it failed since you have a lot of catch exception in there. Could you test it out with the event directly in Lambda to view the logs?

  • The code isn't very clear on where it failed since you have a lot of catch exception in there. Could you test it out with the event directly in Lambda to view the logs?

沒有答案

您尚未登入。 登入 去張貼答案。

一個好的回答可以清楚地回答問題並提供建設性的意見回饋,同時有助於提問者的專業成長。

回答問題指南