首页 > 解决方案 > 当 Firestore 发生一些变化时,我想在不刷新页面的情况下更新数据

问题描述

我正在尝试使用 Firestore 创建 REST,我的目标是在我的数据库发生更改时不断更新结果而不刷新页面。

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


const admin = require('firebase-admin')
const servicAccount = require('./firebase-adminsdk.json')
admin.initializeApp({
    credential: admin.credential.cert(servicAccount)
})
const db = admin.firestore()
app.get('/', (req, res) => {
    // SSE Setup
    res.writeHead(200, {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive',
    });
    const doc = db.collection('TestingData').doc('uQZu5OA0XZZQtG0fKSVG');
    const observer = doc.onSnapshot(doc => res.write(doc.data()))
  });
  app.listen(3000)
    

错误:

_http_outgoing.js:696
    throw new ERR_INVALID_ARG_TYPE('first argument',
    ^

TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer or Uint8Array. Received an instance of Object
    at write_ (_http_outgoing.js:696:11)
    at ServerResponse.write (_http_outgoing.js:661:15)
    at C:\Users\Lmaoooooooo\Desktop\Testing Firebase\index.js:19:48
    at DocumentWatch.onNext (C:\Users\Lmaoooooooo\Desktop\Testing Firebase\node_modules\@google-cloud\firestore\build\src\reference.js:417:21)
    at DocumentWatch.pushSnapshot (C:\Users\Lmaoooooooo\Desktop\Testing Firebase\node_modules\@google-cloud\firestore\build\src\watch.js:449:18)
    at DocumentWatch.onData (C:\Users\Lmaoooooooo\Desktop\Testing Firebase\node_modules\@google-cloud\firestore\build\src\watch.js:333:26)
    at PassThrough.<anonymous> (C:\Users\Lmaoooooooo\Desktop\Testing Firebase\node_modules\@google-cloud\firestore\build\src\watch.js:296:26)
    at PassThrough.emit (events.js:315:20)
    at addChunk (_stream_readable.js:309:12)
    at readableAddChunk (_stream_readable.js:284:9) {
  code: 'ERR_INVALID_ARG_TYPE'
}

标签: node.jsrestfirebase-realtime-database

解决方案


您收到的错误非常具有描述性和具体性。res.write()只接受某些参数类型,并且您没有给它一种允许的类型。您正在向它传递一个不允许的对象。

这是因为doc.data()返回一个对象。如果您希望发送对象作为您的响应,那么您可以更改内容以将其作为 JSON 发送,如下所示:

app.get('/', (req, res) => {
    res.writeHead(200, {
        'Content-Type': 'application/json',        // set JSON content-type
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive',
    });
    const doc = db.collection('TestingData').doc('uQZu5OA0XZZQtG0fKSVG');
    const observer = doc.onSnapshot(doc => res.write(JSON.stringify(doc.data())));
});

推荐阅读