边缘函数

CORS(跨源资源共享)浏览器调用支持


要从浏览器调用边缘函数,您需要处理 CORS 预检请求

参考 GitHub 上的示例

推荐配置

我们建议在 _shared 文件夹中添加一个 cors.ts 文件,这样可以方便地在多个函数中复用 CORS 头信息:

1
2
3
4
export const = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',}

然后您可以在函数中导入并使用这些 CORS 头信息:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import { corsHeaders } from '../_shared/cors.ts'console.log(`Function "browser-with-cors" up and running!`)Deno.serve(async (req) => { // 如果计划从浏览器调用函数,则需要此部分 if (req.method === 'OPTIONS') { return new Response('ok', { headers: corsHeaders }) } try { const { name } = await req.json() const data = { message: `Hello ${name}!`, } return new Response(JSON.stringify(data), { headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 200, }) } catch (error) { return new Response(JSON.stringify({ error: error.message }), { headers: { ...corsHeaders, 'Content-Type': 'application/json' }, status: 400, }) }})