从获取请求中提取数据并将其导出

Idr*_*rne 6 javascript resultset fetch vue.js vuex

我很高兴加入 StackOverFlow 社区。

我是 Web 开发的新手,有数十亿个问题。

我的问题将涉及 javascript 中的 fetch 请求。

我正在尝试从响应中提取数据 (userId) 以将其导出,但我不能。

我试图将 userId 变量设置为 global 但它不起作用。

有没有人可以在这个问题上帮助他。

预先感谢您的回答。

let userId = "";

let loggedUserId = () => {
  let storageToken = localStorage.getItem("groupomania");
  let objJson = JSON.parse(storageToken);
  let token = objJson.token;

  let params = token;

  const headers = new Headers();
  headers.append("Authorization", `Bearer ${token}`);

  let url = "http://localhost:3000/api/user/userId/" + params;

  const parametresDeRequete = {
    method: "GET",
    headers: headers,
  };

  fetch(url, parametresDeRequete)
    .then(function(response) {
      if (response.status !== 200) {
        console.log(
          "Looks like there was a problem. Status Code: " + response.status
        );
        return;
      }

      response.json().then(function(data) {
        userId = data.data;

        console.log(
          "%c ?? Utilities Logged User Id ?? ===>>",
          "color:red ;  font-size: 15px",
          userId
        );
      });
    })

    .catch(function(err) {
      console.log("Fetch Error :-S", err);
    });
};

loggedUserId();
Run Code Online (Sandbox Code Playgroud)

ura*_*hko 3

您需要在第一个中返回response.json()。然后,您将另一个链接到您接收数据的那个(如果有发送给您的)。确保您收到的数据是 json。

\n
fetch(url, parametresDeRequete)\n    .then(function(response) {\n      if (response.status !== 200) {\n        console.log(\n          "Looks like there was a problem. Status Code: " + response.status\n        );\n        return;\n      } else {\n        return response.json(); // returns unresolved Promise\n      }\n     }\n     .then(function(data) {  // data refers to the resolved promise. If the response is not json then the previous .json() method will throw an error which you will be able to catch with .catch()\n        userId = data.id;\n\n        console.log(\n          "%c \xe2\x9a\xa0\xef\xb8\x8f Utilities Logged User Id \xe2\x9a\xa0\xef\xb8\x8f ===>>",\n          "color:red ;  font-size: 15px",\n          userId\n        );\n      });\n    })\n    .catch(function(err) {\n      console.log("Fetch Error :-S", err);\n    });\n
Run Code Online (Sandbox Code Playgroud)\n