I’m trying to run a lambda function from my front-end website but I keep getting a CORS error.
The front-end code that should contact the lambda function is the following:
const handleSubmit = async (e) => {
e.preventDefault();
setIsSubmitting(true);
setSubmitMessage('');
try {
const response = await fetch('https://foobar.lambda-url.eu-west-2.on.aws/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
});
if (response.ok) {
setSubmitMessage('Your request has been submitted successfully!');
setFormData({
name: '',
});
} else {
throw new Error('Form submission failed');
}
} catch (error) {
console.error('Error:', error);
setSubmitMessage('An error occurred. Please try again later.');
} finally {
setIsSubmitting(false);
}
};
The error is the following:
Access to fetch at 'https://foobar.lambda-url.eu-west-2.on.aws/' from origin 'https://my-website.amplifyapp.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.Understand this error
index.js:29
POST https://foobar.lambda-url.eu-west-2.on.aws/ net::ERR_FAILED
index.js:50 Error: TypeError: Failed to fetch
at index.js:29:36
CORS are active on AWS. The thing that I find strange is that the request on the chrome network tab display “Provisional Header are shown”:
And if I use the same parameter but using the terminal and curl
the call goes through without any problem, for example:
curl -X POST 'https://foobar.lambda-url.eu-west-2.on.aws/'
-H 'Content-Type: application/json'
-d '{"name":"test test"}'
Here’s the lambda function:
import { SES } from "@aws-sdk/client-ses";
const ses = new SES({ region: 'eu-west-2' });
export async function handler(event) {
if (event.httpMethod === "OPTIONS") {
return {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type",
"Access-Control-Allow-Methods": "POST, OPTIONS",
},
body: JSON.stringify({ message: "Preflight check successful" }),
};
}
let formData;
if (event.body) {
try {
formData = JSON.parse(event.body);
} catch (error) {
console.error("Error parsing event body:", error);
return {
statusCode: 400,
headers: {
"Access-Control-Allow-Origin": "*",
},
body: JSON.stringify({ message: "Invalid JSON" }),
};
}
} else {
return {
statusCode: 400,
headers: {
"Access-Control-Allow-Origin": "*",
},
body: JSON.stringify({ message: "No body provided" }),
};
}
const params = {
Destination: { ToAddresses: ["my-email-address"] },
Message: {
Body: { Text: { Data: JSON.stringify(formData, null, 2) } },
Subject: { Data: "form info" },
},
Source: "some-user",
};
try {
await ses.sendEmail(params);
return {
statusCode: 200,
body: JSON.stringify({ message: "Email sent successfully" }),
};
} catch (error) {
console.error(error);
} finally {
console.log("finished");
}
}
What am I missing?