CORS Error When Using Lambda + API Gateway + HTML Form

45 views Asked by At

I am attempting to set up a POST lambda function using AWS Lambda and API Gateway. The POST is coming from a form that i've set up on my website, i created the form using this tutorial from codeacademy (https://www.freecodecamp.org/news/how-to-receive-emails-via-your-sites-contact-us-form-with-aws-ses-lambda-api-gateway/).

I keep on getting CORS errors when submitting the form on my site. Ive tried playing around with the config settings on API Gateway and tried many different solutions but none seem to work. Im new to working with API's and this is my first Lambda function so any help would be appreciated.

I've attatched my configuration settings for CORS in API Gateway. CORS Config In API Gateway

The exact error that i get on my browser when trying to submit the form on my website is:

Access to fetch at 'https://kwhn71man3.execute-api.eu-west-2.amazonaws.com/original/BotNestForm' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

This is the request object from my website:

const endpoint = "https://kwhn71man3.execute-api.eu-west-2.amazonaws.com/original/BotNestForm"; 
  const body = JSON.stringify({
    senderName: name.value,
    senderEmail: email.value,
    message: message.value,
  });
  const requestOptions = {
    method: "POST",
    body : JSON.stringify(body),
    headers: {
        "Content-Type": "application/json",
    },
  };

So far i've tried using the CLI to enable CORS for my API as an alternative to the UI on API Gateway. I've also tried adding JSON.stringify(body) to the request object in my JS (to be honest not 100% sure the reasoning but someone on stack overflow said it fixed it for them).

I've also tried manually adding headers in my request object:

"Access-Control-Allow-Origin": "*"

This didnt work either :(

Plz help

1

There are 1 answers

1
VIKAS KATARIYA On

Please try with CORS

const requestOptions = {
    method: "POST",
    body: JSON.stringify(body),
    headers: {
        "Content-Type": "application/json",
    },
    mode: "cors", // Add this
};