Hello,
I have created a Netlify background function to process POST requests. The goal is to receive a POST request, execute my generateEmbeddings
function, and send a response back. However, I am encountering a CORS issue when attempting to make a POST request to my Netlify function. Despite setting the CORS headers in my function, I’m still receiving a Cross-Origin Request Blocked
error. I orginally had this set as a serverls function and not a background function, and did not run into any CORS issues. I had to move to a background function due to request taking more then 10 seconds with bigger requests.
The errors I recieve are the following
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://my-netlify-site.netlify.app/.netlify/functions/webhooks-background. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 202.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://my-netlify-site.netlify.app/.netlify/functions/webhooks-background. (Reason: CORS request did not succeed). Status code: (null).
Here’s the code for my background function:
exports.handler = async (event) => {
const headers = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
"Content-Type": "application/json",
};
if (event.httpMethod === "OPTIONS") {
return {
statusCode: 204,
headers,
body: '',
};
} else if (event.httpMethod === "POST") {
try {
const parsedData = JSON.parse(event.body);
await generateEmbeddings(parsedData);
return {
statusCode: 202,
headers: headers,
body: "Webhook data received",
};
} catch (error) {
console.error("Error handling request:", error);
return {
statusCode: 500,
headers: headers,
body: "Internal Server Error",
};
}
} else {
return {
statusCode: 405,
headers,
body: JSON.stringify({ message: "HTTP Method not supported. Use OPTIONS or POST." }),
};
}
};
Any recommendations would be appreciated!