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

Supabase部署边缘函数后浏览器调用出现CORS错误求助

Supabase边缘函数生产环境CORS跨域问题排查与解决

问题背景

已部署配置CORS响应头的Supabase边缘函数,代码如下:

import { serve } from "server"
import * as cryptojs from "crypto-js";

import { config } from "dotenv";

// Load the environment variables from .env file
await config();

const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
}

serve(async (req) => {
  // This is needed if you're planning to invoke your function from a browser.
  if (req.method === 'OPTIONS') {
    return new Response('ok', { headers: corsHeaders })
  }

  try {

    ...
    ... 
    ...

    return new Response(
      JSON.stringify(data), {
        status: 200,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' },
      }
    )
  } catch (error) {
    return new Response(
      JSON.stringify({ error: error.message || error.toString() }), {
        status: 500,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' },
      }
    );
  }
})

使用Supabase库调用函数:

const response = await supabase.functions.invoke(
                "retrieve-payment-link", {
                    body: {
                        id: payment_link_id,
                    }
                }
            );

部署命令:

npx supabase functions deploy retrieve-payment-link --import-map supabase/functions/import_map.json

本地运行无问题,但生产环境出现错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource

解决方法

1. 核对生产环境响应头

打开浏览器开发者工具的Network面板,查看OPTIONS预请求和实际请求的响应头:

  • 确认Access-Control-Allow-Origin是否正确返回*或你的生产域名
  • 检查请求中实际发送的所有头(比如Supabase调用可能自动添加x-supabase-functions-origin)是否包含在Access-Control-Allow-Headers中

2. 补充完整CORS头配置

扩展corsHeaders,覆盖更多必要的跨域字段:

const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type, x-supabase-functions-origin',
  'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
  'Access-Control-Expose-Headers': 'Content-Length, Content-Type'
}

3. 确保函数部署生效

重新部署函数,指定项目ref确保部署到目标生产环境:

npx supabase functions deploy retrieve-payment-link --import-map supabase/functions/import_map.json --project-ref <你的项目ID>

(项目ID可在Supabase控制台的项目设置页面获取)

4. 检查Supabase项目全局跨域设置

在Supabase控制台的Settings > API页面:

  • 确认Site URL已添加你的生产域名
  • 若需临时测试,可开启Allow all origins(生产环境建议锁定具体域名)

5. 覆盖所有返回路径的CORS头

检查函数代码中所有可能的返回分支(比如try块内的提前return),确保都带上...corsHeaders,避免遗漏。

6. 清除CDN缓存

如果生产环境使用了CDN加速,可能缓存了旧的响应头,需要手动清除CDN缓存或等待缓存过期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 11:02:54