I am trying to send a fetch request to a netlify lambda function from another domain and I’m receiving a the following CORS error: flourishplant.com/:1 Access to XMLHttpRequest at 'https://flourishplant-api.netlify.app/.netlify/functions/klaviyo-fetch-customer' from origin 'https://flourishplant.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
I am returning headers in the status return and have tried adding multiple configurations of the headers to the netlify.toml file as well as adding a _headers file next to the index.html file, but I’m still getting the error. I’ve seen other threads here with similar issues and no resolution – is there something I’m missing that would be causing the error?
Font context, here is my netlify function:
import axios from "axios";
import { statusReturn, headers } from "./utils/requestConfig";
const PRIVATE_TOKEN = process.env.KLAVIYO_API_KEY;
const LIST_ID = process.env.KLAVIYO_LIST_ID;
exports.handler = async (event) => {
if (event.httpMethod !== "POST" || !event.body)
return statusReturn(400, { error: "idk" });
let incomingUser;
try {
incomingUser = JSON.parse(event.body);
if (!incomingUser.hasOwnProperty("user_email")) {
return statusReturn(400, { error: "Missing values in Request Payload" });
}
} catch (error) {
console.log("JSON parsing error:", error);
return statusReturn(400, { error: "Bad request body" });
}
const user_email = incomingUser.user_email;
try {
const fetchMember = await axios({
url: `https://a.klaviyo.com/api/v2/list/${LIST_ID}/get-members?api_key=${PRIVATE_TOKEN}`,
method: "POST",
headers,
data: JSON.stringify({
emails: [user_email],
}),
});
if (fetchMember.data) {
const fetchInfo = await axios({
url: `https://a.klaviyo.com/api/v1/person/${fetchMember.data[0].id}?api_key=${PRIVATE_TOKEN}`,
method: "GET",
headers,
});
return {
statusCode: 200,
headers,
body: JSON.stringify({
success: fetchInfo.data,
}),
};
}
} catch (error) {
console.log("JSON parsing error:", error);
}
};
And this is my requestConfig with headers:
export const headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type',
'Content-Type': 'application/json',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',
}
export const statusReturn = (code, body) => {
return {
statusCode: code,
headers,
body: JSON.stringify(body)
}
}