sourcecode

가져오기 요청에서 데이터를 추출하여 내보냅니다.

copyscript 2022. 7. 27. 23:53
반응형

가져오기 요청에서 데이터를 추출하여 내보냅니다.

Stack Over Flow 커뮤니티에 가입하게 되어 기쁩니다.

웹 개발은 처음이라 질문이 많습니다.

제 질문은 javascript의 fetch request에 관한 것입니다.

내보내기 위해 응답에서 데이터(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();

먼저 response.json()을 반환해야 합니다.그런 다음 데이터를 수신하는 데이터(전송된 데이터가 있는 경우)에 다른 체인을 연결합니다.수신한 데이터가 json인지 확인합니다.

fetch(url, parametresDeRequete)
    .then(function(response) {
      if (response.status !== 200) {
        console.log(
          "Looks like there was a problem. Status Code: " + response.status
        );
        return;
      } else {
        return response.json(); // returns unresolved Promise
      }
     }
     .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()
        userId = data.id;

        console.log(
          "%c ⚠️ Utilities Logged User Id ⚠️ ===>>",
          "color:red ;  font-size: 15px",
          userId
        );
      });
    })
    .catch(function(err) {
      console.log("Fetch Error :-S", err);
    });

언급URL : https://stackoverflow.com/questions/66881742/extract-the-data-from-a-fetch-request-and-export-it

반응형