You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用Supabase Edge函数时遭遇CORS错误求助

解决Supabase Edge函数CORS错误问题

问题原因

你的Edge函数默认代码未处理跨域资源共享(CORS)相关请求头,也未响应浏览器发送的OPTIONS预检请求,导致浏览器拦截跨域请求。

解决方案

修改Edge函数代码,添加CORS头并处理OPTIONS请求:

import { serve } from "https://deno.land/std@0.168.0/http/server.ts";

console.log("Hello from Functions!");

// 开发环境可临时用*,生产环境替换为你的前端域名(如https://your-app.com)
const ALLOWED_ORIGIN = "http://localhost:5173";

serve(async (req) => {
  // 处理OPTIONS预检请求
  if (req.method === "OPTIONS") {
    return new Response(null, {
      headers: {
        "Access-Control-Allow-Origin": ALLOWED_ORIGIN,
        "Access-Control-Allow-Methods": "POST, OPTIONS",
        "Access-Control-Allow-Headers": "Content-Type, Authorization",
      },
    });
  }

  try {
    const { name } = await req.json();
    const data = {
      message: `Hello ${name}!`,
    };

    return new Response(JSON.stringify(data), {
      headers: {
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": ALLOWED_ORIGIN,
      },
    });
  } catch (err) {
    return new Response(JSON.stringify({ error: err.message }), {
      status: 400,
      headers: {
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": ALLOWED_ORIGIN,
      },
    });
  }
});

关键说明

  • OPTIONS请求处理:浏览器发起跨域POST请求前,会先发送OPTIONS预检请求确认服务器是否允许跨域,必须返回包含CORS允许头的响应。
  • Access-Control-Allow-Origin:指定允许的前端域名,开发环境用*方便测试,但生产环境必须设置为具体域名,避免安全风险。
  • 响应头统一添加:所有成功或错误的响应都要带上Access-Control-Allow-Origin头,确保浏览器能正常接收响应。

内容的提问来源于stack exchange,提问作者Sebastian Trygg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 05:47:22