我正在开发一个简单的 Nextjs 应用程序,该应用程序对 firebase firestore 数据库进行一些 CRUD 操作,我使用 zustand 进行状态管理,但是当我尝试添加文档时,我收到错误代码 400 (错误的请求)在控制台中(下面附有图片)
这是代码
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 };
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;
简单的表格
"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;
}
}
}
GitHub 存储库 >> https://github.com/Shailendra1703/fb
经过几天的调试,我发现我的环境有一个额外的逗号,因为我的 firestore db 对象没有正确设置,从而导致了这个错误。
欲了解更多信息,您可以访问此 github 讨论>> https://github.com/firebase/firebase-js-sdk/discussions/8352