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

React+Firebase全栈项目运行firebase serve时遇TypeError问题求助

Firebase Cloud Functions 报错:Cannot read properties of undefined (reading 'fromDate')

问题场景

在Mac上开发React+Firebase全栈项目,执行firebase serve启动本地模拟器后,调用createQuestion接口触发TypeError,错误提示为Cannot read properties of undefined (reading 'fromDate'),对应index.js第38行。

我的index.js代码

const functions = require("firebase-functions");
const admin = require("firebase-admin");

admin.initializeApp();

const express = require('express');
const app = express();

app.get('/questions', (req, res) => {
    admin
        .firestore()
        .collection('Business Continuity Form ')
        .get()
        .then((data) => {
            let questions = [];
            data.forEach((doc) => {
                questions.push(doc.data());
            });
            return res.json(questions);
        })
        .catch((err) => console.error(err));
});

exports.createQuestion = functions.https.onRequest((req, res) => {
    if (req.method !== 'POST') {
        return res.status(400).json({ error: 'Method not allowed' });
    }
    const newQuestion = {
        body: req.body.body,
        userHandle: req.body.userHandle,
        createdAt: admin.firestore.Timestamp.fromDate(new Date())
    };

    admin
        .firestore()
        .collection('Business Continuity Form ')
        .add(newQuestion)
        .then((doc) => {
            res.json({ message: `document ${doc.id} created successfully` });
        })
        .catch((err) => {
            res.status(500).json({ error: 'something went wrong' });
            console.error(err);
        });
});

exports.api = functions.https.onRequest(app);

终端错误信息

⚠  functions: The Cloud Firestore emulator is not running, so calls to Firestore will affect production.
⚠  functions: TypeError: Cannot read properties of undefined (reading 'fromDate')
at /Users/BAYPLS.GUEST/Desktop/business-continuity/functions/index.js:38:46
at cloudFunction (/Users/BAYPLS.GUEST/Desktop/business-continuity/functions/node_modules/firebase-functions/lib/v1/providers/https.js:51:16)
at /Users/BAYPLS.GUEST/.cache/firebase/tools/lib/node_modules/firebase-tools/lib/emulator/functionsEmulatorRuntime.js:532:16
at runFunction (/Users/BAYPLS.GUEST/.cache/firebase/tools/lib/node_modules/firebase-tools/lib/emulator/functionsEmulatorRuntime.js:506:15)
at runHTTPS (/Users/BAYPLS.GUEST/.cache/firebase/tools/lib/node_modules/firebase-tools/lib/emulator/functionsEmulatorRuntime.js:531:11)
at /Users/BAYPLS.GUEST/.cache/firebase/tools/lib/node_modules/firebase-tools/lib/emulator/functionsEmulatorRuntime.js:690:27
at Layer.handle [as handle_request] (/Users/BAYPLS.GUEST/.cache/firebase/tools/lib/node_modules/firebase-tools/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/BAYPLS.GUEST/.cache/firebase/tools/lib/node_modules/firebase-tools/node_modules/express/lib/router/route.js:144:13)
at next (/Users/BAYPLS.GUEST/.cache/firebase/tools/lib/node_modules/firebase-tools/node_modules/express/lib/router/route.js:140:7)
at next (/Users/BAYPLS.GUEST/.cache/firebase/tools/lib/node_modules/firebase-tools/node_modules/express/lib/router/route.js:140:7)
⚠  Your function was killed because it raised an unhandled error.
i  Request to function failed: Error: socket hang up

预期结果

调用createQuestion接口后,返回类似以下内容的成功提示:

{"message": "document z24ronfurnfou23r created successfully"}

解决方案

1. 修复Timestamp引用问题

报错核心原因是admin.firestore.Timestamp未被正确识别,推荐使用Firebase内置的服务器时间戳替代手动创建,既避免版本兼容问题,又能获取更准确的服务器时间:

// 替换原newQuestion中的createdAt字段
const newQuestion = {
    body: req.body.body,
    userHandle: req.body.userHandle,
    createdAt: admin.firestore.FieldValue.serverTimestamp()
};

若坚持手动创建Timestamp,需确保firebase-admin版本为v8及以上,执行升级命令:

npm install firebase-admin@latest --save

之后可直接导入Timestamp使用:

const { Timestamp } = require('firebase-admin/firestore');
// 然后修改createdAt
createdAt: Timestamp.fromDate(new Date())

2. 配置Express JSON解析中间件

原代码未配置解析POST请求体的中间件,会导致req.body为undefined,进而无法获取请求参数。需在初始化Express后添加:

const express = require('express');
const app = express();
// 添加这行代码
app.use(express.json());

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 18:36:25