获取请求用户名 firebase [VUE]

Get request username firebase [VUE]

我正在尝试使用 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相匹配。据我所知,我实际上是在数据库中找到了正确的用户,但是我找不到用户名的任何地方。第二个屏幕截图是我得到的响应。我试图打开响应中的几乎所有选项,但没有地方可以找到数据库中的名称。

我知道我遗漏了一些可能非常简单的东西,但我似乎无法弄明白。你们能帮帮我吗?

编辑: 我试图找到另一种方法来做到这一点,我正在返回所有用户的列表(反正不会那么多)然后我使用 for 循环遍历每个条目。请参阅下面的代码:

const responseUser = await fetch(
  `https://[firebase-link].firebasedatabase.app/users.json`,
  {
    method: "GET",
  }
);

// 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: a call with fetch returns a Promise containing the response (a Response object). Then, to extract the JSON body content from the response, the doc indicates that you need to use the json() 方法的文档,其中“returns 一个使用 JavaScript 对象解析的 Promise,该对象是将正文文本解析为 JSON".

文档显示了以下示例,使用了两次 then() 方法(即链接承诺),因为返回了两个承诺,如上所述。

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);