问题描述
我正在尝试使用 Firebase 设置一个数据库,该数据库也有一个用户名字段。我正在使用 Google (https://cloud.google.com/identity-platform/docs/reference/rest/v1/accounts/signInWithPassword) 的身份工具包来执行注册和登录操作。但据我所知,我无法在注册数据库中存储用户名,因为我无法更改表格和内容。这就是我制作自己的 Firebase 数据库的原因(见图,该数据库中的数据是通过 POST 请求存储的)。我想要做的是通过 GET 请求获取用户名。
我可以建立与我自己的 Firebase 数据库的连接并获得正常响应。我正在使用以下代码执行此操作:
const responseUser = await fetch(
`https://[firebase-link].firebasedatabase.app/users/${userId}.json`,{
method: "GET",}
);
当我登录时收到响应,状态为 200(这似乎是一个正确的连接)。在 console.log 中,我还可以清楚地看到我在请求中使用的相应 userId,它与数据库中的 userId 匹配。所以据我所知,我实际上是在数据库中找到了正确的用户,但是我找不到可以找到 userName 的地方。第二个屏幕截图是我得到的回应。我已经尝试打开响应中的几乎所有选项,但是我找不到数据库中的名称。
我知道我遗漏了一些可能非常简单的东西,但我似乎无法弄清楚。你们能帮我吗?
编辑: 我试图找到另一种方法来做到这一点,我正在返回所有用户的列表(无论如何都不会那么多),然后我使用 for 循环来遍历每个条目。见下面的代码:
const responseUser = await fetch(
`https://[firebase-link].firebasedatabase.app/users.json`,}
);
// console.log(responseUser);
const responseUserData = await responseUser.json();
// console.log("ResponseUserData ===");
// console.log(responseUserData);
for (let userData in responseUserData) {
let userId = responseData.localId;
console.log("== userId");
console.log(userId); // returns the user ID I need to filter the userData on
console.log("== full user item");
console.log(userData); // returns the user item,which contains userId and userName
console.log("---------------------------------");
// How do I filter to get the userName of userItem with corresponding userId?
}
现在我需要做的就是过滤 userItem,就像我在代码的最后一条评论中所说的那样。怎么样?
我尝试通过以下方式过滤:
const user = responseUserData.filter(user => user.userId === userId)
console.log(user);
但这给了我一个错误 Uncaught (in promise) TypeError: responseUserData.filter is not a function
解决方法
查看 Fetch API 的文档:使用 fetch 的调用返回包含响应的 Promise(Response
对象)。然后,要从响应中提取 JSON 正文内容,该文档指出您需要使用 json()
方法,该方法“返回一个使用 JavaScript 对象解析的 Promise,该对象是将正文文本解析为 JSON 的结果”。
该文档显示了以下示例,使用了两次 then()
方法(即链接 Promise),因为返回了两个 Promise,如上所述。
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));
在您的情况下,由于您使用 async/await
,以下内容可以解决问题:
const response = await fetch(
`https://[firebase-link].firebasedatabase.app/users/${userId}.json`,{
method: 'GET',}
);
const responseData = await response.json();
console.log(responseData);
console.log(responseData.userName);