News API
News API에 가서 API Key를 받은 뒤,
Documentation > Endpoints > Everything
위 링크로 가서 examples 코드를 변수 url
에 넣어준다.
그리고 백틱을 통해, q=
부분에는 사용자의 input.value를 넣고, apiKey=
에는 본인의 apiKey값을 넣으면 된다.
fetch로 data를 받아와서 로그를 찍어보고 원하는 데이터를 html 요소에 집어 넣으면 된다.
skeleton
https://cdnjs.com/libraries/skeleton
retrieve() 함수 구현
a 요소를 만들고, a.setAttribute를 통해 링크랑 target까지 넣은 후에 추가하기
.container > .news-list에 li 요소들을 검색되는 대로 추가하기
a의 target 속성 : 링크된 문서가 열렸을 때, 열리는 방식 설정(_blank를 넣으면 새로운 윈도우나 탭으로 열리도록)
입력 단어에 따라 링크들이 보여주고 사라지고 해야 하므로,
함수 실행 전에 기존에 띄워진 값들을 지워줘야 한다.
(newsList.innerHTML = '';
)
e.preventDefault()
: 해당 이벤트에 대한 브라우저(사용자 에이전트)의 기본 동작을 실행하지 않도록 지정하는 것임.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.css">
<link rel="stylesheet" href="style.css">
<title>newsAPI</title>
</head>
<body>
<form class="search" action="">
<label for="">News</label>
<input class="input" type="text" /><br>
<input type="submit" />
</form>
<div class="container">
<ul class="news-list"></ul>
</div>
<script>
const searchFrom = document.querySelector('.search');
const input = document.querySelector('.input');
const newsList = document.querySelector('.news-list');
searchFrom.addEventListener('submit', retrieve);
function retrieve(e) {
if (input.value == '') {
alert('Input field is empty!!');
return;
}
newsList.innerHTML = '';
e.preventDefault();
const apiKey = '자신의 apiKey를 여기에 입력';
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);
newsList.appendChild(li);
})
})
.catch((error) => {
console.log(error);
})
// console.log(topic);
}
</script>
</body>
</html>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
list-style: none;
}
.search {
position: absolute;
top: 10%;
left: 10%;
}
.container {
position: absolute;
top: 40%;
left: 10%;
}
have you ever used https://newsdata.io/ news api??