Fetch JSON

jb kim·2021년 11월 10일
0

JSON & AJAX

목록 보기
15/22

Fetch로 대체

        var joker = document.querySelector('#btn');
        joker.addEventListener('click', loadJoke)

        function loadJoke() {
            const url = 'https://api.chucknorris.io/jokes/random';
            
            fetch(url).then(function (response) {
                console.log(response.headers.get('Content-Type'))
                console.log(response.headers.get('Date'))
                console.log(response.type)
                return response.json()
                 }).then(function (json) {
                console.log(json)
                let html = '<div><img src="'+json.icon_url+'"> '+json.value+'</div>';
                document.querySelector('#output').innerHTML = html;
            }).catch(function(error){
                console.log(error);
            })

Fetch 사용법
https://developer.mozilla.org/ko/docs/Web/API/Fetch_API/Using_Fetch

익명함수 => 화살표 함수(자바람다식)

        var joker = document.querySelector('#btn');
        var output = document.querySelector("#output");
        joker.addEventListener('click', loadJoke);

        function loadJoke() {
            const url = 'https://api.chucknorris.io/jokes/random';
            
            fetch('https://api.chucknorris.io/jokes/random')
                .then(resJSON)
                .then(json => output.innerHTML = `<div><img src="${json.icon_url}"> ${json.value} </div>`)
                .catch(error => console.log(error))
               
            function resJSON(response){
                return response.json()
            }
        }

화살표 함수

참고자료
https://ko.javascript.info/fetch

https://medium.com/@armando_amador/how-to-make-http-requests-using-fetch-api-and-promises-b0ca7370a444

profile
픽서

0개의 댓글