[DAY - 61] API(jsonplaceholder, news, pixabay)

2023. 5. 30. 20:50·🔥 부트캠프-웹 개발 🔥/JavaScript_advanced
  • jsonplaceholder
  • news
  • pixabay

 

1) jsonplaceholder

jsonplaceholder post api를 이용해 게시판을 만들어 보았다.

 

https://jsonplaceholder.typicode.com/

 

JSONPlaceholder - Free Fake REST API

{JSON} Placeholder Free fake API for testing and prototyping. Powered by JSON Server + LowDB. Tested with XV. Serving ~2 billion requests each month.

jsonplaceholder.typicode.com

jsonplaceholder

    <script>
        const tbody = document.querySelector('.board .table-body');
        const paging = document.querySelector('.board .paging');
        const url = 'https://jsonplaceholder.typicode.com/posts';

        let posts, postsPerPage = 10, currentPage = 1
        let firstPost, lastPost, postMod, pageNumber, totalPage
        let a = '';

        const getData = async () => {
            const res = await fetch(url);
            const myJson = await res.json();

            posts = myJson;
            totalPage = posts.length;
            postMod = totalPage % postsPerPage;
            pageNumber = Math.ceil(totalPage / postsPerPage)

            for (let i = 1; i <= pageNumber; i++) {
                a += `<a>${i}</a>`
            }
            paging.innerHTML = a

            tableIn(currentPage)

            let aAll = document.querySelectorAll('.paging a')
            aAll[currentPage - 1].classList.add('on')
            let old = 0;
            aAll.forEach((item, idx) => {
                item.addEventListener('click', e => {
                    let ele = e.currentTarget
                    if (old !== idx) {
                        ele.classList.add('on')
                        aAll[old].classList.remove('on')
                        tableIn(idx + 1)
                        old = idx
                    }
                })
            })
        }

        function tableIn(currentPage) {
            console.log(currentPage)
            let row = '';
            lastPost = currentPage * postsPerPage;
            firstPost = lastPost - postsPerPage;

            if (postMod !== 0 && currentPage === pageNumber) {
                lastPost = firstPost + postMod
            }

            for (let i = firstPost; i < lastPost; i++) {
                row += `<tr>
                        <td> ${posts[i].id} </td>
                        <td> ${posts[i].title} </td>
                        <td> ${posts[i].body} </td>
                    </tr>
                `
            }
            tbody.innerHTML = row;
        }

        getData();
    </script>

 

await와 fetch를 사용해 비동기통신을 하고, 총 페이지와 페이지당 표시될 post 숫자를 계산해 게시판 하단에 paging 버튼을 추가해 준다.

 

            let aAll = document.querySelectorAll('.paging a')
            aAll[currentPage - 1].classList.add('on')
            let old = 0;
            aAll.forEach((item, idx) => {
                item.addEventListener('click', e => {
                    let ele = e.currentTarget
                    if (old !== idx) {
                        ele.classList.add('on')
                        aAll[old].classList.remove('on')
                        tableIn(idx + 1)
                        old = idx
                    }
                })
            })

 

그 뒤에 버튼 클릭 시 class가 add 되게 해 준다.

마지막으로 tableIn 함수에서는 currentPage를 매개변수로 받아 page에 맞는 post 번호만 tbody에 출력되게 해 주었다.

 

 

 

2) news

https://newsapi.org/s/south-korea-news-api

 

South Korea News API - Live top headlines from South Korea

Get live top and breaking news headlines from South Korea with our JSON API. Live example This example demonstrates the HTTP request to make, and the JSON response you will receive, when you use the News API to get live headlines from South Korea. Top head

newsapi.org

news

<body>
    <main id="container" class="news">
        <section id="content">
            <div class="inner">
                <!-- <article>
                    <a href="">
                        <h2>타이틀</h2>
                        <img src="" alt="">
                        <p></p>
                    </a>
                </article> -->
            </div>
        </section>
    </main>
    <script>
        const article = document.querySelector('.inner')
        const url = 'https://newsapi.org/v2/top-headlines?country=kr
        fetch(url)
        .then(res=>res.json())
        .then(res=>{
            console.log(res.articles);
            listIn(res.articles)
        })

        function listIn(data) {
            for (let i = 0; i < data.length; i++) {
                article.innerHTML += `
                    <article>
                    <a href="${data[i].url}}">
                        <h2>${data[i].title}</h2>
                        <img src="${data[i].urlToImage}" alt="">
                        <p>${data[i].description}</p>
                    </a>
                </article>
                `
            }
        }
    </script>
</body>

 

 

3) pixabay

 

https://pixabay.com/api/docs/

 

Pixabay API Documentation

lang str Language code of the language to be searched in. Accepted values: cs, da, de, en, es, fr, id, it, hu, nl, no, pl, pt, ro, sk, fi, sv, tr, vi, th, bg, ru, el, ja, ko, zh Default: "en" category str Filter results by category. Accepted values: backgr

pixabay.com

 

    <script>
        let conBox = document.querySelector('.con-box')
        let search = document.querySelector('#text')
        let form = document.querySelector('#form')
        let searchBtn = document.querySelector('button')
        let url, keyword;

        const getData = async(keyword='')=>{
            url = `https://pixabay.com/api/?key==${keyword}&image_type=photo`;
            const res = await fetch(url)
            const myJson = await res.json();
            show(myJson.hits)
        }

        function show(data) {
            conBox.innerHTML = '';
            for (let i = 0; i < data.length; i++) {
                let tages = data[i].tags.split(',');
                conBox.innerHTML += `
                  <article>
                    <div>
                      <img src="${data[i].largeImageURL}" alt="">
                    </div>
                    <h3>${data[i].user}</h3>
                    <ul>
                      <li><span>view</span>:<em>${data[i].views}</em></li>
                      <li><span>download</span>:<em>${data[i].downloads}</em></li>
                      <li><span>like</span>:<em>${data[i].likes}</em></li>
                    </ul>
                    <p>
                      <span>#${tages[0]}</span>
                      <span>#${tages[1]}</span>
                      <span>#${tages[2]}</span>
                    </p>
                  </article>
                `;
            }
        }
        form.addEventListener('submit', e => {
            e.preventDefault();
            keyword = search.value;
            getData(keyword);
        });
    </script>

 

pixabay api의 경우 검색하고자 하는 키워드를  url에 넣으면 이미지를 불러와 준다.

 

        const getData = async(keyword='')=>{
            url = `https://pixabay.com/api/?key==${keyword}&image_type=photo`;
            const res = await fetch(url)
            const myJson = await res.json();
            show(myJson.hits)
        }

 

따라서 input으로 받은 keyword를 url에 넣어주었다.

처음 keyword는 async(keyword=' ')으로 공백이므로 첫 화면엔 아무것도 출력이 되지 않는다.

 

 

* form에 event를 걸 경우 출력 후 새로고침이 되므로 preventDefault()를 넣어주어야 한다.

e.preventDefault();

 

 

만약 input에 keyword를 넣고 search 버튼을 눌렀을 때 같은 결과를 나오게 하고 싶다면 아래 코드를 추가하면 된다.

 

        searchBtn.addEventListener('click', e => {
            e.preventDefault();
            keyword = search.value;
            getData(keyword);
        });
'🔥 부트캠프-웹 개발 🔥/JavaScript_advanced' 카테고리의 다른 글
  • [DAY - 64] localStorage 기초, localStorage 형식변환, localStorage 예제
  • [DAY - 63] module 사용법, import default, module 합치기, module 예제
  • [DAY - 59] async / await, fetch, axios, insertAdjacentHTML, 데이터 출력 예제
  • [DAY - 58] static, private, try / catch
Yeonhub
Yeonhub
✨ https://github.com/yeonhub 📧 lsy3237@gmail.com
  • Yeonhub
    비 전공자의 Be developer
    Yeonhub
  • 전체
    오늘
    어제
    • 전체보기 (169)
      • 🔍 Tech 🔍 (19)
        • Front-End (11)
        • Back-End (4)
        • AI (1)
        • Server (1)
        • Etc (2)
      • 💡 원티드 프리온보딩 챌린지 💡 (14)
        • PRE-ONBOARDING_AI (11월) (1)
        • PRE-ONBOARDING_FE (2월) (2)
        • PRE-ONBOARDING_FE (1월) (2)
        • PRE-ONBOARDING_FE (12월) (9)
      • 🔥 부트캠프-웹 개발 🔥 (118)
        • HTML5 (7)
        • CSS3 (21)
        • JavaScript (27)
        • JavaScript_advanced (9)
        • React (24)
        • Next (1)
        • MYSql (5)
        • Node (5)
        • 오늘하날(개인프로젝트) (12)
        • 이젠제주투어(팀프로젝트) (7)
      • 💻 CS 💻 (1)
        • 알고리즘 (1)
      • ⚡ 코딩테스트 ⚡ (11)
        • JavaScript (11)
      • 📚 Books 📚 (6)
        • 클린 아키텍처 (2)
        • 인사이드 자바스크립트 (4)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

    • Github
  • 공지사항

  • 인기 글

  • 태그

    javascript fcm
    Node
    expo 길찾기
    rn bottom sheet
    php node
    node.js fcm
    bottom sheet
    expo admob
    react native bottom sheet
    react native expo fcm
    컴파운드 컴포넌트 패턴
    expo deep linking
    node crontab
    react vite
    expo fcm push
    node fcm
    expo google map
    react native admob
    라스콘4
    expo fcm
    프론트엔드 테스트코드
    react native firebase analytics
    node cron
    python node
    react native analytics
    expo map
    expo 지도
    라스콘
    rn admob
    expo node fcm
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Yeonhub
[DAY - 61] API(jsonplaceholder, news, pixabay)
상단으로

티스토리툴바