CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200

0

Hi all, I'm having trouble with a Contact Form, I can't get it to work properly.
This is my setup: Route53, Cloudfront(with certificate attached), S3(for the static content), API Gateway, Lambda, DynamoDB.

  1. A node.js script takes the form data from the html and sends it to the API gateway
  2. API gateway sends it to Lambda
  3. Lambda writes the data in DynamoDB

This is the javascript code to fetch the form data:

var email = document.getElementById('email').value.trim();
  var subject = document.getElementById('subject').value.trim();
  var message = document.getElementById('message').value.trim();

  // Email validation using a regular expression
  var emailRegex = /^\S+@\S+\.\S+$/;
  if (!name || !email || !subject || !message || !emailRegex.test(email)) {
    alert('Please fill in all fields with valid inputs.');
    return;
  }

  // Construct the form data
  var formData = {
    name: name,
    email: email,
    subject: subject,
    message: message
  };

  // Perform form submission
  submitForm(formData);
});

function submitForm(formData) {
  // Make an API request to the backend (API Gateway) for form submission
  fetch('https://helloworld.execute-api.us-east-1.amazonaws.com/dev/submit', { 
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(formData),
    mode: 'cors',  // Enable CORS
    credentials: 'same-origin', 
    origin: 'https://site.com' 
  })
  .then(function(response) {
    if (response.ok) {
      // Redirect to the thank you page
      window.location.href = 'thank-you.html';
    } else {
      throw new Error('Form submission failed.');
    }
  })
  .catch(function(error) {
    console.error(error);
    alert('Form submission failed. Please try again later.');
  });
}

When I hit submit the contact form the data is being written in DynamoDB properly so I should be redirected to "thank-you.html" but i'm getting "Form submission failed. Please try again later" instead. On the debugging console in Firefox I see:

"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource athttps://helloworld.execute-api.us-east-1.amazonaws.com/dev/submit. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200."

and

"TypeError: NetworkError when attempting to fetch resource. scripts2.js:50:13
    submitForm https://site.com/scripts2.js:50
    (Async: promise callback)
    submitForm https://site.com/scripts2.js:49
    <anonymous> https://site.com/scripts2.js:26"

In Cloudwatch Logs for the API Gateway there are no errors, there is: Method completed with status: 200

any idea???

2 Answers
1
Accepted Answer

In your Lambda, be sure to return the expected headers in the response:

export const handler = async (event) => {

  // Write to DynamoDB

    const response = {
        statusCode: 200,
        headers: {
            "Access-Control-Allow-Headers" : "Content-Type",
            "Access-Control-Allow-Origin": "https://www.example.com", // Be sure to add the correct origin here
            "Access-Control-Allow-Methods": "OPTIONS,POST,GET"
        },
        body: JSON.stringify(myResponseObject),
    };
    return response;
};
profile pictureAWS
EXPERT
answered 2 months ago
  • It's working now many thanks! I included the above code but also looking at the API gateway's Method Response there was just 1 header configured(Access-Control-Allow-Origin), I added the other 2 and saved it, then redeployed the API gateway and voila :)

0

Hello.

It seems that a CORS error is occurring. Have you configured CORS on the API Gateway side?
In this case, it seems that "Access-Control-Allow-Origin" is not allowed, so please try setting "Access-Control-Allow-Origin" to "*".
https://repost.aws/knowledge-center/api-gateway-cors-errors
https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html

profile picture
EXPERT
answered 2 months ago
  • Initially I was having issues on not getting the form data inserted into dynamoDB, the API gateway was not allowing the data to go to the lambda function, and I as getting an error code 500 so I redeployed the API Gateway, configured CORS as "*", did the same on the S3 bucket and Cloudfront, after that the data is being allowed on the API Gateway and it's being written successfully on DynamoDB. On Cloudwatch logs everything is fine no errors and everything is shown as successful but for some reason the javascript is not getting back the response code OK 200 so it thinks the operation was unsuccessful therefore it's not redirecting me to the thank-you.html

  • Since API Gateway is working without errors, I think the problem is with the front end. Can you check if the response from API Gateway includes CORS headers in your browser's developer tools?

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions