javascript - Firebase/Angular:从 Firebase 存储读取 JSON 文件
问题描述
我正在编写一个与标准 Firebase 设置(Auth/Firestore)连接的 Angular 10 应用程序,到目前为止一切都很好。
我有一个外部应用程序,它将一个 JSON 文件上传到存储桶,我希望能够直接从我的 Angular 应用程序中读取它。
问题是当我执行 HTTP GET 请求时,我得到了 403 响应。
======这是我的代码======
我的.service.ts:
const url = 'https://firebasestorage.googleapis.com/v0/b/my-project/o/test%2Fbehaviors.json?alt=media&auth='+this.ss.getCurrentToken();
const headers = new Headers({
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.ss.getCurrentToken()}`
});
const collection2 = this.http.get(url, { headers: headers })
.pipe(
map(behaviors => {
console.log(behaviors)
})
);
Firebase 存储规则
rules_version = '2';
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if false;
}
match /test/{allPaths=**} {
allow read: if request.auth != null; // note if I set TRUE directly it s working but without auth
allow write: if false;
}
}
}
==================
任何人都可以通过授权设置直接读取 JSON 文件吗?
解决方案
啊啊啊。
经过几个小时的测试、阅读文档和脱发,我终于明白了这个问题。
在 JSON 文件的 url 中,令牌部分专用于 Firebase 存储中文件的“版本”,与用户令牌无关。
解决方案是:
- 使用 fireStorageservice 首先获取文件的令牌
- 获取下载地址
- 然后执行正常的 HTTP 获取请求。
这里是我的服务中链调用的代码示例:
const this.fs.ref('test/behaviors.json').getDownloadURL()
.pipe(
switchMap((url) => {
return this.http.get(url)
.pipe(
map(behaviors => {
console.log(behaviors)
const pList = [];
Object.keys(behaviors).forEach(doc => {
pList[behaviors[doc].key] = behaviors[doc];
});
return pList;
})
)
})
);
推荐阅读
- css - 如何增加 rshiny 仪表板侧边栏菜单项之间的填充边距?
- python - 熊猫提取价值变化的前一行
- symfony - 为什么在 prod mod 的 symfony 5.3 中出现 503 错误,而在 dev mod 中却没有
- javascript - 会话存储问题
- firebase - 不允许读取您在 firebase 数据库中读取的特定密钥
- go - 在嵌套 golang 结构中使用指针
- php - 为什么 MySQL 中的这个更新在 PHP 中没有正确完成?
- javascript - 想知道使用带有 node.js 的 JS 在网页上获取用户输入然后使用该输入进行网页抓取的最佳方式
- php - 如何访问提交数据并将其提交给第三方 API?
- python - 如何让输出向后打印?