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

本地运行正常但Firebase部署后报JSON解析错误求助

问题排查与解决方案

核心错误原因

你的React前端部署到Firebase托管后,fetch('https://translatebrain.com/')请求的是Firebase托管的静态前端页面(返回HTML),而非你的Express后端API,因此调用res.json()解析HTML文本时会抛出Unexpected token '<'错误。本地运行时前端请求的是本地3001端口的后端服务,所以能正常工作。

分步解决步骤

1. 将Express后端部署为Firebase Functions

Firebase托管仅用于静态资源(你的React前端),后端服务需要部署到Firebase Functions:

  • 初始化Firebase Functions:在项目根目录执行命令:
    firebase init functions
    
    选择JavaScript语言,按需启用ESLint,完成依赖安装。
  • 将你的后端index.js代码迁移到functions/index.js,并适配Firebase Functions的运行逻辑(无需手动指定端口):
    const OpenAI = require('openai')
    const { Configuration, OpenAIApi } = OpenAI;
    const functions = require("firebase-functions");
    const express = require('express');
    const bodyParser = require('body-parser');
    const cors = require('cors');
    const app = express();
    
    // 从Firebase环境变量读取密钥,避免硬编码
    const configuration = new Configuration({
        organization: functions.config().openai.organization,
        apiKey: functions.config().openai.apikey,
    });
    const openai = new OpenAIApi(configuration);
    
    app.use(bodyParser.json());
    app.use(cors());
    
    app.post('/', async (req, res) => {
        const { message, language } = req.body;
        // 修复prompt格式,添加空格避免语法问题
        const prompt = `Translate this into ${language}: ${message}`;
        try {
            const response = await openai.createCompletion({
                model: "text-davinci-003",
                prompt: prompt,
                max_tokens: 100,
                temperature: 0,
            });
            if (response.data.choices[0].text) {
                res.send({ message: response.data.choices[0].text.trim() });
            } else {
                res.status(400).send({ message: '翻译结果为空' });
            }
        } catch (err) {
            res.status(500).send({ message: '服务器错误', error: err.message });
        }
    });
    
    // 导出为Firebase Function
    exports.api = functions.https.onRequest(app);
    

2. 配置Firebase环境变量(关联密钥)

不要在代码中硬编码敏感信息,用Firebase环境变量存储:

  • 在终端执行命令,替换为你的实际密钥:
    firebase functions:config:set openai.apikey="你的OpenAI API密钥" openai.organization="你的OpenAI组织ID"
    
    部署后,Functions会自动读取这些变量。

3. 修正前端fetch地址与参数

修改App.js中的fetch URL为Firebase Functions的地址(格式为https://<你的Firebase项目ID>.cloudfunctions.net/api),同时修复前端未传递language参数的问题:

const handleSubmit = (e) => {
  e.preventDefault();
  // 替换为你的Firebase Functions API地址
  fetch('https://<你的项目ID>.cloudfunctions.net/api', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    // 同时传递message和language参数
    body: JSON.stringify({ message, language })
    
  })
    .then(res => {
      // 先检查响应状态,避免非JSON响应导致错误
      if (!res.ok) throw new Error('请求失败');
      return res.json();
    })
    .then(data => setResponse(data.message))
    .catch(err => console.log(err));
}

4. 重新部署前端与后端

  • 部署前端到Firebase托管:
    npm run build
    firebase deploy --only hosting
    
  • 部署后端Functions:
    firebase deploy --only functions
    

额外注意事项

  • 确保Firebase Functions的部署地区与OpenAI API访问地区适配,避免延迟过高。
  • 前端添加表单验证(如检查message和language是否为空),避免无效请求。
  • 处理后端可能的错误响应,给用户友好提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 18:15:59