Fetch API는 JavaScript의 내장 API로, 서버로부터 데이터를 가져올 떄 사용됩니다.

Fetch API에서 가장 자주 사용되는 메서드는 fetch()입니다. fetch()는 URL을 매개변수로 받아서 서버로부터 데이터를 가져옵니다. fetch() 메서드는 Promise 객체를 반환하며, then()메서드를 사용하여 비동기적으로 처리된 응답(response) 데이터를 처리할 수 있습니다.

fetch().then()의 기본 구문은 다음과 같습니다.


fetch(url)
  .then(response => {
    // 응답(response) 처리
  })
  .catch(error => {
    // 오류(error) 처리
  });


fetch()메서드는 Promise 객체를 반환하므로, then()메서드를 호출하여 Promise가 처리된 후에 실행될 콜백 함수를 등록할 수 있습니다. then()메서드에 전달된 콜백 함수는 응답(response)객체를 매개변수로 받으며, 이 객체를 사용하여 서버로부터 받은 데이터를 처리할 수 있습니다.

then()메서드 체인은 연속적으로 호출할 수 있습니다. 따라서, 여러 개의 then()메서드를 연속적으로 호출하여 여러 개의 비동기적인 작업을 순차적으로 처리할 수 있습니다.

const searchForm = document.querySelector('.search');
const input = document.querySelector('.input')
const newList = document.querySelector('.news-list')

searchForm.addEventListener('submit', retrueve)


function retrueve(e) {

    newList.innerHTML = ''

    e.preventDefault()

    if (input.value === '') {
        alert('Input field is empty')
        return
    }

    const apiKey = "677982bdcd6549329d32edfcb90766bd"
    let topic = input.value;


    let url = `https://newsapi.org/v2/everything?q=${topic}&apiKey=${apiKey}`;

    fetch(url).then((res) => {
        return res.json()
    }).then((data) => {
        console.log(data);
        data.articles.forEach(article => {
            let li = document.createElement('li');
            let a = document.createElement('a');
            a.setAttribute('href', article.url)
            a.setAttribute('target', '_blank');
            a.textContent = article.title;
            li.appendChild(a);
            newList.appendChild(li);
        })
    }).catch((error) => {
        console.log(error);
    })

}

뉴스 검색 API를 이용하여 사용자가 입력한 검색어에 해당하는 뉴스 기사를 검색하여 출력하는 기능을 구현한 코드입니다.

우선, const 키워드를 사용하여 searchForm, input, newList 변수를 초기화합니다. 이 변수들은 각각 HTML 요소들을 나타냅니다. searchForm 변수는 검색어를 입력하는 폼(form) 요소, input 변수는 검색어를 입력하는 입력(input) 요소, newList 변수는 검색 결과를 출력하는 리스트(list) 요소를 나타냅니다.

다음으로, searchForm 변수에 이벤트 리스너를 등록합니다. 이벤트 리스너는 submit 이벤트가 발생했을 때 retrueve() 함수를 호출합니다.

retrueve() 함수는 먼저 newList 요소의 내용을 모두 지우고(innerHTML = ''), 이벤트의 기본 동작을 중지하기 위해 e.preventDefault()를 호출합니다.

그 다음, 검색어 입력값이 비어있는 경우에는 경고창을 띄우고 함수를 종료합니다(if (input.value === '')).

검색어 입력값이 존재하는 경우에는, newsapi.org에서 발급받은 API 키를 사용하여 검색어에 해당하는 뉴스 기사들을 검색합니다. 검색어를 포함하는 URL을 생성한 후, fetch() 메서드를 사용하여 API에 요청을 보내고, res.json() 메서드를 사용하여 응답을 JSON 형식으로 변환합니다.

JSON 데이터를 처리하기 위해 Promise의 then() 메서드를 사용합니다. 첫 번째 then() 메서드에서는 반환된 JSON 데이터를 콘솔에 출력합니다(console.log(data)). 두 번째 then() 메서드에서는 data.articles 배열을 순회하며, 각각의 뉴스 기사에 대한 정보를 리스트(newList)에 추가합니다. 이때, document.createElement() 메서드와 document.createTextNode() 메서드를 사용하여 요소와 텍스트를 생성한 후, DOM 요소들을 조작합니다.

API 요청이 실패한 경우에는 catch() 메서드에서 에러를 콘솔에 출력합니다(console.log(error)).

profile
신은 인간에게 선물을 줄 때 시련이라는 포장지에 싸서 준다. 선물이 클수록 더 큰 포장지에 싸여있다. - 브라이언 트레이시 -

0개의 댓글