Skip to content

Unable to call Edge Function

如果你在调用 Edge Function 时遇到问题或出现 CORS 问题,可以按照以下步骤来诊断和解决问题。

🌐 If you're having trouble invoking an Edge Function or experiencing CORS issues, follow these steps to diagnose and resolve the problem.

查出问题 #

🌐 Diagnose the issue

  1. 检查 CORS 配置: 查看 CORS 指南,确保你已正确配置 CORS 头
  2. 检查函数日志: 在仪表板的 函数 > 日志 中查找错误
  3. **验证身份:**确认 JWT 令牌和权限是否正确

正确处理跨源资源共享 #

🌐 Proper CORS handling

确保你的函数能处理 OPTIONS 预检请求。

🌐 Make sure your function handles OPTIONS preflight requests.

🌐 Recommended (v2.95.0+)

1
// Recommended approach
2
import { corsHeaders } from '@supabase/supabase-js/cors' // v2.95.0+
3
4
Deno.serve(async (req) => {
5
if (req.method === 'OPTIONS') {
6
return new Response('ok', { headers: corsHeaders })
7
}
8
9
// Your function logic here
10
return new Response(JSON.stringify({ status: 'Success' }), {
11
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
12
})
13
})

在 2.95.0 之前的版本 #

🌐 For versions before 2.95.0

如果你在 v2.95.0 之前使用 @supabase/supabase-js,你需要硬编码 CORS 头。在 _shared 文件夹 内添加一个 cors.ts 文件:

🌐 If you're using @supabase/supabase-js before v2.95.0, you'll need to hardcode the CORS headers. Add a cors.ts file within a _shared folder:

1
// _shared/cors.ts
2
export const corsHeaders = {
3
'Access-Control-Allow-Origin': '*',
4
'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
5
}

然后在你的函数中导入它:

🌐 Then import it in your function:

1
import { corsHeaders } from '../_shared/cors.ts'
2
3
Deno.serve(async (req) => {
4
// Handle CORS preflight requests
5
if (req.method === 'OPTIONS') {
6
return new Response('ok', { headers: corsHeaders })
7
}
8
9
// Your function logic here
10
return new Response(JSON.stringify({ status: 'Success' }), {
11
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
12
})
13
})

调试工具 #

🌐 Debugging tools

Supabase 为 Edge Functions 提供了两个调试工具:

🌐 Supabase provides two debugging tools for Edge Functions:

  • 调用: 显示每次执行的请求和响应
  • 日志: 显示平台事件,包括部署和错误

在仪表板中,进入 功能 > [你的功能] 来访问这些工具。

🌐 Access these tools by navigating to Functions > [Your Function] in the dashboard.

常见问题 #

🌐 Common issues

CORS 错误 #

🌐 CORS errors

  • 响应中缺少 Access-Control-Allow-Origin
  • 没有处理 OPTIONS 预检请求
  • 允许的方法或头部不匹配

身份验证错误 #

🌐 Authentication errors

  • 无效或已过期的 JWT 令牌
  • 缺少授权头
  • 经过身份验证的用户权限不正确

网络错误 #

🌐 Network errors

  • 功能未部署
  • 函数网址不正确
  • 网络连接问题

额外资源 #

🌐 Additional resources