支持从浏览器调用的跨域资源共享(CORS)
要从浏览器调用边缘函数,你需要处理 CORS 预检 请求。
🌐 To invoke edge functions from the browser, you need to handle CORS Preflight requests.
自动处理 CORS #
🌐 Automatic CORS handling
withSupabase 封装器会帮你处理 CORS 和预检 (OPTIONS) 请求,所以你不用手动添加头信息:
🌐 The withSupabase wrapper handles CORS and preflight (OPTIONS) requests for you, so you don't add headers manually:
1import { withSupabase } from 'npm:@supabase/server@^1'23export default {4 fetch: withSupabase({ auth: 'user' }, async (req, ctx) => {5 const { name } = await req.json()6 return Response.json({ message: `Hello ${name}!` })7 }),8}手动处理 CORS #
🌐 Manual CORS handling
如果你的函数没有使用 withSupabase,就自己添加头文件。看看 GitHub 上的例子。
🌐 If your function doesn't use withSupabase, add the headers yourself. See the example on GitHub.
对于 @supabase/supabase-js v2.95.0 及更高版本: 直接从 SDK 导入 CORS 头,以确保它们与客户端库中添加的任何新头保持同步。
从 npm:@supabase/supabase-js@^2/cors 导入 corsHeaders,就能自动获取所有需要的头文件:
🌐 Import corsHeaders from npm:@supabase/supabase-js@^2/cors to automatically get all required headers:
1import { corsHeaders } from 'npm:@supabase/supabase-js@^2/cors'23console.log(`Function "browser-with-cors" up and running!`)45export default {6 fetch: async (req) => {7 // Handle the CORS preflight request.8 if (req.method === 'OPTIONS') {9 return Response.json({ ok: true }, { headers: corsHeaders })10 }1112 try {13 const { name } = await req.json()14 return Response.json({ message: `Hello ${name}!` }, { headers: corsHeaders })15 } catch (error) {16 return Response.json({ error: error.message }, { status: 400, headers: corsHeaders })17 }18 },19}这种方法可以确保当向 Supabase SDK 添加新头时,你的 Edge 函数会自动包含它们,从而防止 CORS 错误。
🌐 This approach ensures that when new headers are added to the Supabase SDK, your Edge Functions automatically include them, preventing CORS errors.
在 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:
1export const corsHeaders = {2 'Access-Control-Allow-Origin': '*',3 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',4}然后在你的函数中导入它:
🌐 Then import it in your function:
1import { corsHeaders } from '../_shared/cors.ts'23// ... rest of your function code