如何连接firestore

问题描述 投票:0回答:1

我是 firebase 新手,我正在尝试使用 firestore 获取 next.js 应用程序的数据,但出现错误。

这是错误:

TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:11730:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  cause: AggregateError
      at internalConnectMultiple (node:net:1114:18)
      at afterConnectMultiple (node:net:1667:5)
      at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
    code: 'ECONNREFUSED',
    [errors]: [ [Error], [Error] ]
  }
}

这是代码:

import React from 'react';
import { initializeApp } from 'firebase/app'
import {
  getFirestore, collection, getDocs
} from 'firebase/firestore'




const firebaseConfig = {
    apiKey: process.env.API_KEY,
    authDomain: "social-app-a0aef.firebaseapp.com",
    projectId: "social-app-a0aef",
    storageBucket: "social-app-a0aef.appspot.com",
    messagingSenderId: "106093296170",
    appId: "1:106093296170:web:852948bb8d8fd86ccfe153"
  };

// init firebase
const app = initializeApp(firebaseConfig)

// init services
const db = getFirestore(app)

// collection ref
const colRef = collection(db, "books")

// get collection data


async function Firebase() {

    try {
        const snapshot = await getDocs(colRef)
        snapshot.forEach((doc) => {
            console.log(doc.data)
        })
    } catch (err) {
        console.error("firebase error:", err)
    }

    

  return (
    <div></div>
  )
}

export default Firebase

我检查了 .env.local 文件、数据库状态,并尝试捕获详细错误,但无法解决问题。

firebase google-cloud-firestore next.js
1个回答
0
投票

如果您使用 NextJS 并尝试在客户端上初始化 firebase(您应该这样做),则需要使用前缀

NEXT_PUBLIC_
标签访问 .env 环境变量。

尝试在配置中对 Api 密钥进行硬编码以进行测试。

© www.soinside.com 2019 - 2024. All rights reserved.