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?

No hay respuestas

No has iniciado sesión. Iniciar sesión para publicar una respuesta.

Una buena respuesta responde claramente a la pregunta, proporciona comentarios constructivos y fomenta el crecimiento profesional en la persona que hace la pregunta.

Pautas para responder preguntas