리셋 되지 말자

fetch API 본문

web

fetch API

kyeongjun-dev 2020. 9. 24. 15:39

fetch API 기본 사용법

웹서버를 열어서 fetch.html을 연다. (아파치 톰캣을 이용했다.)

  • fetch.html
<!DOCTYPE html>
<html>
    <body>
        <article>

        </article>
        <input type="button" value="fetch" onclick="
            fetch('html').then(function(response){
                response.text().then(function(text){
                    alert(text);
                    document.querySelector('article').innerHTML=text;
                })
            })
        ">
    </body>
</html>

'html'이라는 파일을 서버에 요청하고, 응답이 끝나면 그 응답이 콜백함수에 담겨서 'text'라는 인자에 파일의 내용이 담겨온다 라고 일단 이해하고 넘어가자

fetch.html파일이 있는 경로에 html이라는 파일이 존재한다. 내용은 아래와 같다.

 

  • html
<h2>html is ...<h2>

 

  • 접속화면

 

  • fetch 버튼 클릭

html 파일의 내용 alert
article 태그에 html의 텍스트 내용 추가됨

 

fetch API의 원리(요청과 응답)

fetch('html')

client가 'html'이라는 파일을 서버로부터 달라고 웹브라우저에게 요청한다.

네트워크 탭을 확인하면, html 파일을 가져온 것을 확인할 수 있다.

        <input type="button" value="fetch" onclick="
            function callbackFunction(){
                alert(`I am callback`);
            };
            fetch('html').then(callbackFunction);
        ">

.then은 fetch('html')이 끝나면 즉, 요청을 한 뒤 응답이 끝나면 then의 괄호(인자)를 실행하라는 의미다.

그래서 위의 결과로, html 파일을 받으면 'callbackFuntion()'이 실행되어 'I am callback'이 alert 된다.

  • then 동작 확인하기
<!DOCTYPE html>
<html>
    <body>
        <article>

        </article>
        <input type="button" value="fetch" onclick="
            // fetch('html').then(function(response){
            //     response.text().then(function(text){
            //         alert(text);
            //         document.querySelector('article').innerHTML=text;
            //     })
            // })
            function callbackFunction(){
                console.log(`I am callback`);
            };
            fetch('html').then(callbackFunction);
            console.log(1);
            console.log(2);
        ">
    </body>
</html>

위처럼 코드를 작성하면 위에서부터 순차적으로 console에 'I am callback'후 1과 2가 출력되어야 할것 같지만, .then은 예약의 개념, 응답이 끝나면 callbackFunction() 함수가 실행이 되므로 결과가 예상한 것과 다르다.

1과 2가 먼저 찍히는 것을 확인할 수 있다. = 비동기적으로 동작한다.

 

fetch API - response 객체

fetch API를 사용할 때, .then의 인자로 콜백함수를 지정한다. 그리고 그 콜백함수의 인자로 response 객체를 받아오는데 이를 아래 코드를 이용하여 콘솔에 출력해본다.

<!DOCTYPE html>
<html>
    <body>
        <article>

        </article>
        <input type="button" value="fetch" onclick="
            function callbackFunction(){
                console.log(`I am callback`);
            };
            fetch('html').then(function(response){
                console.log(response);
            });
        ">
    </body>
</html>

결과는 진짜로 'Response'라는 객체가 콘솔에 출력되었다. (status가 200이면 파일을 잘 찾았다는, 성공이라는 의미다. 찾지 못하면 404 반환)

없는 파일을 요청했을 때 404 반환

https://ko.javascript.info/fetch

 

'web' 카테고리의 다른 글

SSL/TLS 무료 인증서 발급 사이트  (0) 2021.09.07
[javascript] 하위 태그(요소) 삭제하기  (0) 2020.06.02
[js] 배열(Array) 다루기  (0) 2020.05.29
Comments