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

Nuxt3生产环境(Firebase)中readBody()报500错误求助

Nuxt3部署Firebase Hosting后API路由500错误修复方案

问题定位

本地运行正常,但部署到Firebase Hosting后调用/api/chat-completion返回500错误,错误提示请求体参数类型不符合预期。经排查问题出在服务端readBody()函数,核心原因是Firebase的Serverless环境与本地Nuxt环境对请求体的解析逻辑存在差异。

解决方案

1. 客户端显式指定请求格式

在$fetch调用中明确设置Content-Type并手动序列化请求对象,避免Firebase环境下的解析歧义:

async function doSomething(formData: ApplicationInfo) {
  if (userStore.userData.credits > 0) {
    try {
      const data = await $fetch<string>('/api/chat-completion', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(formData)
      })

      if (data) {
        // 业务逻辑处理
      }
    } catch (e) {
      console.error('请求错误:', e)
    }
  } else {
    // 无可用credits的处理逻辑
  }
}

2. 服务端手动解析原始请求体

若客户端调整后仍无效,可绕过readBody(),直接读取原始请求体并手动解析:

import { ApplicationInfo } from '../../types/applicationInfo.interface'
import { readRawBody } from 'h3'

export default defineEventHandler(async (event): Promise<string> => {
  const rawBodyBuffer = await readRawBody(event)
  const body: ApplicationInfo = JSON.parse(rawBodyBuffer.toString())
  const response = await chatCompletion(body)
  return response
})

3. 验证Firebase部署配置

确保firebase.json中的路由转发配置正确指向Nuxt的SSR服务:

{
  "hosting": {
    "public": ".output/public",
    "ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
    "rewrites": [
      {
        "source": "**",
        "function": "server"
      }
    ]
  },
  "functions": {
    "source": ".output/server"
  }
}

同时确认部署时使用npm run build && firebase deploy命令,且Cloud Functions的Node.js版本与本地开发环境一致(推荐v18及以上)。

额外排查建议

临时在服务端添加日志,确认解析后的请求体结构是否符合预期:

export default defineEventHandler(async (event): Promise<string> => {
  const body: ApplicationInfo = await readBody<ApplicationInfo>(event)
  console.log('解析后的请求体:', body)
  console.log('请求体类型:', typeof body)
  const response = await chatCompletion(body)
  return response
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 01:38:34