Firebase Realtime Rest API with JavaScript



Firebase文档有一些有用的curl操作,但没有提供有关使用JS Fetch的Cors、Header和auth的信息。我们正在使用一个仅获取的解决方案,因为我正在创建一个基于客户端的Firebase npm包,其中用户可能由于多种原因(树抖动、缩小项目等(而没有导入Firebase模块。

我想我需要把Auth作为一个标题,那么Cors和凭据呢?

这里有一个粗略的例子,这足够吗?或者还有其他不可预见的问题吗?

const pushOptions = {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}
var dataAPI = await fetch(databaseUrl+`/test.json`,pushOptions)
.then(response => response.json())

参考:

  • https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
  • https://firebase.google.com/docs/reference/rest/database#section-看跌

文档说明您需要在查询参数'access_token'中传递Firebase ID,而不是在任何头中传递。例如,

curl 'https://[PROJECT_ID].firebaseio/users/jack/name.json?access_token=CREDENTIAL'

但我最终得到了Unauthorized错误。

然而,Firebase Auth REST API文档中的Authenticate with a ID Token部分说;将上面生成的ID令牌作为auth=<ID_TOKEN>查询字符串参数"。同样的卷曲请求示例是:

curl 'https://[PROJECT_ID].firebaseio/users/jack/name.json?auth=CREDENTIAL'

此请求按预期进行。

关于CORS,这个答案说,

Firebase使用完全允许的跨来源资源共享(CORS(策略,这意味着您可以从任何来源向Firebase服务器发出请求。这是可能的,因为Firebase不使用cookie或传统会话来管理哪些请求被授权,哪些请求未被授权。

下面是一个使用Javascript提取的工作示例:

firebase.auth().onAuthStateChanged(async (user) => {
const token = await firebase.auth().currentUser.getIdToken()

const pushOptions = {
method: 'GET',
}
const reqURL = "https://[PROJECT_ID].firebaseio.com" + `/path.json?auth=${token}`
const dataAPI = await fetch(reqURL, pushOptions)
.then(response => response.json())
.then(res => console.log(res))
})

我只是使用客户端SDK快速获取ID令牌,但无论令牌是从哪里生成的——客户端SDK还是Auth REST API,它都能工作。

REST API接受客户端SDK使用的相同Firebase ID令牌。

最新更新