Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

JavaScript GET 요청:Fetch API 사용

개발자는 종종 자체 API 또는 타사 API에서 데이터를 검색해야 합니다. 이 문서에서는 브라우저의 Fetch API를 사용하여 엔드포인트에서 일부 데이터를 가져오는 방법에 대해 설명합니다.

Fetch API란 무엇입니까?

Fetch API는 Chrome이나 Firefox와 같은 웹 브라우저에서 서버에 HTTP 요청을 할 수 있는 인터페이스입니다. GET 요청은 서버의 엔드포인트에 도달한 다음 읽을 수 있도록 해당 엔드포인트의 데이터와 함께 응답을 반환합니다.

요청 유형

GET HTTP 요청은 서버에 보낼 수 있는 요청 유형 중 하나일 뿐입니다. 다른 유형의 요청은 POST, PUT 및 DELETE입니다. 이러한 요청은 CRUD 애플리케이션을 만듭니다. 데이터베이스에서 데이터를 생성(POST), 읽기(GET), 업데이트(PUT) 및 삭제(DELETE)할 수 있는 곳입니다.

또한 타사 API에서 엔드포인트에 도달할 수 있습니다. API에 따라 주로 데이터를 변경할 수 없는 상태로 유지하기 위해 특정 요청만 수행할 수 있으므로 데이터를 조작하는 요청은 수행할 수 없고 읽을 수만 있습니다.

Fetch API는 어떻게 작동하나요?

Fetch API는 Promise 기반 통신 시스템을 사용합니다. 다시 말씀드리지만, Promise는 로직을 코드 블록으로 캡슐화하고 Promise가 해결 또는 거부되었는지 여부를 결정하는 응답을 반환하는 비동기 함수입니다.

Fetch API의 사용자로서 우리는 실제로 Promise 로직을 작성할 필요가 없습니다. 요청을 보내는 데 사용하기만 하면 Fetch API가 내부적으로 약속을 반환합니다. 응답을 얻을 수 있는 기본 구문은 다음과 같습니다.

promise.then(response).then(json).catch(오류);

약속은 실제 비동기 요청입니다. fetch() 메서드는 전역 범위에서 사용할 수 있으며 HTTP 요청을 하려는 끝점에 전달됩니다.

참가자의 81%는 부트캠프에 참석한 후 기술 직업 전망에 대해 더 자신감을 느꼈다고 말했습니다. 지금 부트캠프에 참여하십시오.

부트캠프 졸업생은 부트캠프 시작부터 첫 직장을 찾는 데까지 6개월도 채 걸리지 않았습니다.

let promise = fetch("https://swapi.dev/api/films/1");

요청 후, then과 함께 promise 구문을 사용하고 서버의 응답을 받기 위해 async/await 함수를 catch하거나 사용할 수 있습니다.

약속 구문

promise.then(response => {
       if (response.status !== 200) {
           console.log('Looks like there was a problem. Status Code: ' +
             response.status);
           return;
       }
           response.json().then(data => {
               console.log(data);
           }).catch(error => {
               console.log(error.message);
           })
 
 
      
     })

여기서 우리는 약속을 받고 응답을 기다립니다. 응답을 받았을 때 상태 코드가 200이 아닌 경우 콘솔에 오류 코드를 기록하고 함수를 종료합니다.

그렇지 않으면 프론트엔드 웹사이트에서 사용할 수 있도록 응답을 읽을 수 있도록 json()을 사용하여 JSON(JavaScript Object Notation) 개체로 변경합니다. 방법. 계속 진행하기 전에 이것이 먼저 평가되기를 원하므로 약속을 이전 약속에 연결합니다.

일단 평가되면 전달된 내용을 기록하여 콘솔에서 볼 수 있습니다. 따라하면 다음과 같이 표시됩니다.

{
       title: 'A New Hope',
       episode_id: 4,
       opening_crawl: 'It is a period of civil war.\r\n' +
         'Rebel spaceships, striking\r\n' +
         'from a hidden base, have won\r\n' +
         'their first victory against\r\n' +
         'the evil Galactic Empire.\r\n' +
         '\r\n' +
         'During the battle, Rebel\r\n' +
         'spies managed to steal secret\r\n' +
         "plans to the Empire's\r\n" +
         'ultimate weapon, the DEATH\r\n' +
         'STAR, an armored space\r\n' +
         'station with enough power\r\n' +
         'to destroy an entire planet.\r\n' +
         '\r\n' +
         "Pursued by the Empire's\r\n" +
         'sinister agents, Princess\r\n' +
         'Leia races home aboard her\r\n' +
         'starship, custodian of the\r\n' +
         'stolen plans that can save her\r\n' +
         'people and restore\r\n' +
         'freedom to the galaxy....',
       director: 'George Lucas',
       producer: 'Gary Kurtz, Rick McCallum',
       release_date: '1977-05-25',
       characters: [
         'https://swapi.dev/api/people/1/',
         'https://swapi.dev/api/people/2/',
         'https://swapi.dev/api/people/3/',
         'https://swapi.dev/api/people/4/',
         'https://swapi.dev/api/people/5/',
         'https://swapi.dev/api/people/6/',
         'https://swapi.dev/api/people/7/',
         'https://swapi.dev/api/people/8/',
         'https://swapi.dev/api/people/9/',
         'https://swapi.dev/api/people/10/',
         'https://swapi.dev/api/people/12/',
         'https://swapi.dev/api/people/13/',
         'https://swapi.dev/api/people/14/',
         'https://swapi.dev/api/people/15/',
         'https://swapi.dev/api/people/16/',
         'https://swapi.dev/api/people/18/',
         'https://swapi.dev/api/people/19/',
         'https://swapi.dev/api/people/81/'
       ],
       planets: [
         'https://swapi.dev/api/planets/1/',
         'https://swapi.dev/api/planets/2/',
         'https://swapi.dev/api/planets/3/'
       ],
       starships: [
         'https://swapi.dev/api/starships/2/',
         'https://swapi.dev/api/starships/3/',
         'https://swapi.dev/api/starships/5/',
         'https://swapi.dev/api/starships/9/',
         'https://swapi.dev/api/starships/10/',
         'https://swapi.dev/api/starships/11/',
         'https://swapi.dev/api/starships/12/',
         'https://swapi.dev/api/starships/13/'
       ],
       vehicles: [
         'https://swapi.dev/api/vehicles/4/',
         'https://swapi.dev/api/vehicles/6/',
         'https://swapi.dev/api/vehicles/7/',
         'https://swapi.dev/api/vehicles/8/'
       ],
       species: [
         'https://swapi.dev/api/species/1/',
         'https://swapi.dev/api/species/2/',
         'https://swapi.dev/api/species/3/',
         'https://swapi.dev/api/species/4/',
         'https://swapi.dev/api/species/5/'
       ],
       created: '2014-12-10T14:23:31.880000Z',
       edited: '2014-12-20T19:49:45.256000Z',
       url: 'https://swapi.dev/api/films/1/'
     }

프론트엔드에서 이 정보를 얻으면 이 정보를 사용하여 카드나 테이블을 채우거나 원하는 대로 표시할 수 있습니다.

비동기/대기

async/await 함수를 사용하여 동일한 결과를 기록할 수도 있습니다.

let getRequest = async () => {
   try {
       let fetched = await fetch("https://swapi.dev/api/films/1");
       if(fetched) {
           let read = await fetched.json()
           console.log(read);
           return read;
       }
   }
   catch (error) {
       throw new Error(error.message);
   }
}
 
getRequest()

async 키워드는 해당 기능의 일부가 비동기식임을 알려줍니다. wait 키워드에 도달하면 해당 코드 줄이 평가될 때까지 스크립트 실행이 일시 중지됩니다.

두 개의 await가 있습니다. 두 then()와 비교되는 이 함수의 문 우리가 약속 논리에 있었던 문장. 하나의 명령문은 우리가 전달한 URL에서 가져오기가 일어나기를 기다리고, 다른 하나는 가져온 정보가 JSON으로 구문 분석될 때까지 대기합니다. try/catch를 사용합니다. 응답에서 비정상적인 것이 반환될 경우 발생할 수 있는 오류를 포착하기 위해.

최종 메모

Fetch API가 노드 환경에서 작동하려면(예:Visual Studio Code와 같은 IDE를 사용하는 경우) yarn add가 필요합니다. 또는 npm install node-fetch , 가져오기는 브라우저 환경에서만 작동합니다.