Fetch JSON

3781 ワード


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