向Firebase Firestore添加文档时出现400(Bad Request)错误
Next.js 集成 Firestore 添加文档时出现400 Bad Request错误
我正在开发一个简单的Next.js应用,使用Firebase Firestore实现CRUD操作,采用Zustand做状态管理。但尝试添加文档时,控制台弹出400(Bad Request)错误。
以下是相关代码与配置:
1. firebase.js 配置文件
import { initializeApp, getApps, getApp } from "firebase/app"; import { getFirestore } from "firebase/firestore"; import { getStorage } from "firebase/storage"; const firebaseConfig = { apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY, authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN, projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID, storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET, messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID, appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID, }; const app = !getApps().length ? initializeApp(firebaseConfig) : getApp()[0]; const db = getFirestore(app); const storage = getStorage(app); export { app, db, storage };
2. Zustand状态管理文件
"use client"; import { create } from "zustand"; import { collection, addDoc, getDocs } from "firebase/firestore"; import { db, storage } from "@/config/firebase"; const useFirestoreStore = create((set) => ({ documents: [], isLoading: false, error: null, addDocument: async (collectionName, data) => { set({ isLoading: true, error: null }); try { const docRef = await addDoc(collection(db, collectionName), data); set((state) => ({ documents: [...state.documents, { id: docRef.id, ...data }], isLoading: false, })); } catch (error) { set({ error: error.message, isLoading: false }); } }, getDocuments: async (collectionName) => { set({ isLoading: true, error: null }); try { const querySnapshot = await getDocs(collection(db, collectionName)); const docs = querySnapshot.docs.map((doc) => ({ id: doc.id, ...doc.data(), })); set({ documents: docs, isLoading: false }); } catch (error) { set({ error: error.message, isLoading: false }); } }, })); export default useFirestoreStore;
3. 表单组件代码
"use client"; import React, { useState } from "react"; import useFirestoreStore from "@/store/firestore"; import { db } from "@/config/firebase"; export default function Home() { const { documents, isLoading, error, addDocument, getDocuments } = useFirestoreStore(); const [formData, setFormData] = useState({ name: "", age: "" }); const handleAddDocument = async () => { if (!formData.name || !formData.age) { alert("Please fill in all fields"); return; } await addDocument("users", { name: formData.name, age: parseInt(formData.age, 10), }); setFormData({ name: "", age: "" }); // Reset form }; const handleInputChange = (e) => { const { name, value } = e.target; setFormData((prevState) => ({ ...prevState, [name]: value })); }; return ( <div> {isLoading && <p>Loading...</p>} {error && <p>Error: {error}</p>} <form onSubmit={(e) => e.preventDefault()}> <label> Name: <input type="text" name="name" value={formData.name} onChange={handleInputChange} /> </label> <label> Age: <input type="number" name="age" value={formData.age} onChange={handleInputChange} className="text-black" /> </label> <button type="button" onClick={handleAddDocument}> Add User </button> </form> </div> ); }
Firebase Firestore安全规则
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow read, write: if true; } } }
内容的提问来源于stack exchange,提问作者Shailendra Singh
相关产品推荐
相关产品推荐

