Netlify Background Function POST请求CORS问题排查求助
我创建了一个Netlify Background Function处理POST请求,需求是接收请求、执行generateEmbeddings函数并返回响应。切换到Background Function前用Serverless Function时没有CORS问题,但因为大请求耗时超10秒,不得不改用Background Function,现在发起POST请求时遇到跨源被阻止的错误,即使在函数里设置了CORS头也无效。
报错信息
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).
初始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." }), }; } };
后续更新
我已经让Background Function在本地正常运行,但生产环境仍存在CORS问题,核心是请求头配置:本地开发时头设置正确,但生产环境无效,已通过curl验证这一点。
最初在netlify.toml文件中设置头,生产环境未生效,之后改用_headers文件,该文件放置在项目根目录。
更新后的Background Function代码
const { generateEmbeddings } = require("../../scripts/embedding"); exports.handler = async (event) => { if (event.httpMethod === "OPTIONS") { console.log("OPTIONS request received"); return; } if (event.httpMethod === "POST") { try { const parsedData = JSON.parse(event.body); await generateEmbeddings(parsedData); console.log("Webhook data processed in the background"); } catch (error) { console.error("Error handling request:", error); } } };
_headers文件内容
/* Cache-Control: no-cache Access-Control-Allow-Origin: * /.netlify/functions/* Access-Control-Allow-Origin: * Access-Control-Allow-Headers: Content-Type, Authorization Access-Control-Allow-Methods: GET, POST, OPTIONS
内容的提问来源于stack exchange,提问作者Matt

