【问题标题】:Nuxt fetch() for Firestore returns empty arrayFirestore 的 Nuxt fetch() 返回空数组
【发布时间】:2021-06-16 01:31:55
【问题描述】:

我正在使用 fetch() 钩子in Nuxt with Firestore,当在服务器上调用它时,它总是返回一个空数组。如果从客户端调用,它会返回一个填充数组

created(){
  this.$fetch() //called on client, logs populated array and json
},
async fetch(){
  const products = await this.$fire.firestore.collection('products').get();
  const ps = products.docs.map(doc=>doc.data());
  console.log(ps); //logs an empty array on Nuxt SSR

  const res = await fetch(`https://jsonplaceholder.typicode.com/posts/38`)
  const l = await res.json();
  console.log(l); //always logs a value on client or SSR

} 

我可以就这里发生的事情以及如何解决它提供一些指导吗?我觉得很奇怪,对jsonplaceholder 的调用总是返回数据,但对 firebase 的调用却没有。请参阅下面的console 的图像

当按下 CTRL + SHIFT + R 时:

当有热重载或客户端导航时:

products.vue

<template>
  <v-container>
    <h1>Products</h1>
    <v-row>
      <v-col v-for="product in products" :key="product.id" cols="3">
        <v-card>
          <v-card-title>
            {{ product.category }}
          </v-card-title>
        </v-card>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
export default {
  data() {
    return {
      products: '',
    }
  },

  async fetch() {
    const products = await this.$fire.firestore.collection('products').get()
    this.products = products.docs.map((doc) => {
      return { ...doc.data(), id: doc.id, ref: doc.ref }
    })

    const res = await fetch(`https://jsonplaceholder.typicode.com/posts/38`)
    const l = await res.json()
  },
  // fetchOnServer: false
}
</script>

【问题讨论】:

  • 你试过使用 asyncData 吗?
  • @Dharmaraj asyncData 正在阻止渲染,而不是实际调用。两者都在服务器+客户端上运行。此外,这两个 API 在这里都称为客户端。测试服务器端将是:拥有 SSR 并禁用 JS 以查看发送到浏览器的 HTML。

标签: javascript firebase google-cloud-firestore nuxt.js hook


【解决方案1】:

你为什么在这里使用created()?您可能可以删除它。

你可能也需要await products.docs.map(doc=&gt;doc.data())

您可以随时使用fetchOnServer: false 将其删除,如下所示:https://nuxtjs.org/docs/2.x/components-glossary/pages-fetch/#options

另外,您可以尝试在仅 node.js 的文件中运行 firebase 代码,看看它是否是服务器。

【讨论】:

  • 我使用 created just 作为再次调用$fetch 的自动方式。好像我在模板上有一个按钮,单击该按钮会调用$fetch。如果 $fire 只是客户端插件,它不会出错吗?
  • 嗯,这正在工作client + server 这边如图所示:firebase.nuxtjs.org/guide/usage#fire 所以让我们来配置可能性,也许你在这里错过了什么:firebase.nuxtjs.org/service-options/firestore?你检查过网络标签吗?你有ssr: true 对吗?
  • 我不认为 ssr:true 适用于 Firestore,仅适用于身份验证。无论如何我没有它并且添加它似乎没有做任何事情
  • 实际上是的,不知道为什么,但 SSR 完全不在讨论范围内。因为我们实际上并没有在服务器端做任何事情,而只是在 fetch() 钩子中。其他解决方案,上面的问题(答案+ cmets)呢?尤其是网络标签。
  • 感谢您的帮助!如果我弄清楚了,我会在这里发帖
猜你喜欢
  • 2019-12-11
  • 2019-07-22
  • 1970-01-01
  • 2021-05-21
  • 1970-01-01
  • 1970-01-01
  • 2022-12-22
  • 2021-03-26
  • 2019-09-26
相关资源
最近更新 更多