node.js - 当 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'
}
解决方案
您收到的错误非常具有描述性和具体性。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())));
});
推荐阅读
- r - -3.39999999999999996e+38 NODATA 值和栅格 R
- c++ - OpenGL中一个对象上的两个图像
- php - 没有布局的 Zend 框架 ajax 请求
- flutter - Flutter Web - 无法编译应用程序
- python - 编写使用带有均值或直接相乘的 pandas Dataframe 计算加权平均值的方法
- json - 如何从 Powershell 中的 XML 文件中的元素中提取和解析属性
- javascript - 尝试使用 Ajax 删除文件
- azure - 在 azure Devops 中从运行时传递参数时,Yaml 编译变量不起作用
- reactjs - 如果令牌在反应 js 中的任何时候过期,则登录并重定向
- amazon-web-services - EFS 有时会返回空文件