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

调用Supabase Edge Functions时出现"Unexpected end of JSON input"错误

解决Supabase Edge函数调用时req.json()报"Unexpected end of JSON input"错误

问题分析

该错误通常意味着Edge函数接收到的请求体为空或格式不符合JSON规范,常见原因包括请求头配置冲突、CORS拦截、请求参数无效等。

修复方案

1. 移除手动设置的Content-Type请求头

Supabase functions.invoke 方法会自动为JSON格式的请求体设置正确的Content-Type: application/json头,手动添加反而可能导致解析异常。修改前端调用代码:

await supabase.functions.invoke('order', {
  body: { order_id: order_id }
})

2. 完善Edge函数的CORS配置

不完整的CORS响应头会导致浏览器拦截请求体,使后端接收不到有效内容。确保CORS头包含必要字段:

const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
  "Access-Control-Allow-Methods": "POST, OPTIONS"
};

Deno.serve(async (req: Request) => {
  if (req.method === 'OPTIONS') {
    return new Response('ok', { headers: corsHeaders, status: 200 })
  } 
  try {
    const { order_id } = await req.json();
    // 业务逻辑处理
    return new Response(JSON.stringify({ success: true, order_id }), {
      headers: { ...corsHeaders, 'Content-Type': 'application/json' },
      status: 200
    })
  } catch (err) {
    return new Response(JSON.stringify({ error: err.message }), {
      headers: { ...corsHeaders, 'Content-Type': 'application/json' },
      status: 400
    })
  }
})

3. 校验前端order_id的有效性

若order_id未定义或为空,传递的请求体可能无法被正常序列化。调用前添加参数校验:

if (!order_id) {
  console.error('order_id 参数未定义或为空');
  return;
}
await supabase.functions.invoke('order', {
  body: { order_id: order_id }
})

4. 禁止手动JSON.stringify请求体

Supabase invoke 方法接受对象类型的body参数,并自动完成序列化。手动使用JSON.stringify会导致双重序列化,后端解析时出现错误,需避免这种写法:

// 错误示例:不要这么做
await supabase.functions.invoke('order', {
  body: JSON.stringify({ order_id: order_id })
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 10:18:26